import { fileURLToPath as __fileURLToPath } from 'url';
import { dirname as __pathDirname } from 'path';
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __pathDirname(__filename);
import { Command } from "commander";
import chalk from "chalk";
import * as path from "path";
import Database from "better-sqlite3";
import { existsSync } from "fs";
import { FrameManager } from "../../core/context/index.js";
import { workflowTemplates } from "../../core/frame/workflow-templates.js";
import { sessionManager } from "../../core/session/session-manager.js";
function createWorkflowCommand() {
  const cmd = new Command("workflow").description("Manage structured workflow templates").option("-l, --list", "List available workflow templates").option("-s, --start <template>", "Start a new workflow from template").option("--status", "Show status of active workflow").action(async (options) => {
    try {
      const projectRoot = process.cwd();
      const dbPath = path.join(projectRoot, ".stackmemory", "context.db");
      if (!existsSync(dbPath)) {
        console.error(chalk.red("\u2717 StackMemory not initialized"));
        console.log(chalk.yellow("Run: stackmemory init"));
        if (process.env["NODE_ENV"] !== "test") {
          process.exit(1);
        }
        return;
      }
      if (options.list) {
        await listWorkflows();
      } else if (options.start) {
        await startWorkflow(options.start, dbPath);
      } else if (options.status) {
        await showWorkflowStatus(dbPath);
      } else {
        await listWorkflows();
      }
    } catch (error) {
      console.error(chalk.red("Error: " + error.message));
      if (process.env["NODE_ENV"] !== "test") {
        process.exit(1);
      }
    }
  });
  return cmd;
}
async function listWorkflows() {
  console.log(chalk.bold("\n\u{1F4CB} Available Workflows"));
  console.log("\u2500".repeat(40));
  Object.entries(workflowTemplates).forEach(([key, template]) => {
    console.log(chalk.cyan(`
${key}:`));
    console.log(`  ${template.description}`);
    console.log(chalk.gray(`  Phases: ${template.phases.length}`));
    template.phases.slice(0, 3).forEach((phase) => {
      console.log(`    \u2022 ${phase.name}`);
    });
    if (template.phases.length > 3) {
      console.log(`    ... and ${template.phases.length - 3} more`);
    }
  });
  console.log(
    chalk.gray("\nStart a workflow: stackmemory workflow --start <name>")
  );
}
async function startWorkflow(workflowName, dbPath) {
  const template = workflowTemplates[workflowName];
  if (!template) {
    console.error(chalk.red(`Unknown workflow: ${workflowName}`));
    console.log(chalk.yellow("Use --list to see available workflows"));
    if (process.env["NODE_ENV"] !== "test") {
      process.exit(1);
    }
    return;
  }
  const db = new Database(dbPath);
  try {
    await sessionManager.initialize();
    const session = await sessionManager.getOrCreateSession({
      projectPath: process.cwd()
    });
    const frameManager = new FrameManager(db, session.projectId);
    const workflowId = await frameManager.createFrame({
      type: "workflow",
      name: `${template.name} Workflow`,
      metadata: {
        workflow: workflowName,
        phases: template.phases.map((p) => p.name),
        currentPhase: 0,
        startTime: Date.now()
      }
    });
    console.log(chalk.green(`\u2713 Started ${workflowName} workflow`));
    console.log(chalk.cyan(`Workflow ID: ${workflowId}`));
    console.log("\nPhases:");
    template.phases.forEach((phase, index) => {
      const marker = index === 0 ? "\u2192" : " ";
      console.log(`${marker} ${index + 1}. ${phase.name}`);
    });
    console.log(chalk.gray("\nTrack progress: stackmemory workflow --status"));
  } finally {
    db.close();
  }
}
async function showWorkflowStatus(dbPath) {
  const db = new Database(dbPath);
  try {
    const workflows = db.prepare(
      `
      SELECT * FROM frames 
      WHERE type = 'workflow' 
      AND state = 'active'
      ORDER BY created_at DESC
    `
    ).all();
    if (workflows.length === 0) {
      console.log(chalk.yellow("No active workflows"));
      return;
    }
    console.log(chalk.bold("\n\u{1F504} Active Workflows"));
    console.log("\u2500".repeat(40));
    workflows.forEach((workflow) => {
      const metadata = workflow.metadata ? JSON.parse(workflow.metadata) : {};
      const elapsed = Date.now() - workflow.created_at;
      const minutes = Math.floor(elapsed / 6e4);
      console.log(chalk.cyan(`
${workflow.name}`));
      console.log(`  ID: ${workflow.frame_id}`);
      console.log(`  Duration: ${minutes} minutes`);
      if (metadata.phases) {
        const current = metadata.currentPhase || 0;
        console.log(`  Phase: ${current + 1}/${metadata.phases.length}`);
        console.log(`  Current: ${metadata.phases[current]}`);
      }
    });
  } finally {
    db.close();
  }
}
var workflow_default = createWorkflowCommand;
export {
  createWorkflowCommand,
  workflow_default as default
};
//# sourceMappingURL=workflow.js.map
