#!/usr/bin/env node
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const commander_1 = require("commander");
const chalk_1 = __importDefault(require("chalk"));
const dotenv = __importStar(require("dotenv"));
const dotenvExpand = __importStar(require("dotenv-expand"));
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
// Load environment variables from local project IMMEDIATELY
try {
    const cwd = process.cwd();
    const candidates = [
        path.join(cwd, ".mycontext", ".env.local"),
        path.join(cwd, ".mycontext", ".env"),
        path.join(cwd, ".env.local"),
        path.join(cwd, ".env"),
    ];
    for (const p of candidates) {
        if (fs.existsSync(p)) {
            const result = dotenv.config({ path: p });
            dotenvExpand.expand(result);
        }
    }
}
catch { }
const init_1 = require("./commands/init");
const init_interactive_1 = require("./commands/init-interactive");
const validate_1 = require("./commands/validate");
const status_1 = require("./commands/status");
const generate_components_1 = require("./commands/generate-components");
const auth_1 = require("./commands/auth");
const enhance_1 = require("./commands/enhance");
const refine_1 = require("./commands/refine");
const setup_1 = require("./commands/setup");
const update_1 = require("./commands/update");
const clean_1 = require("./utils/clean");
const analyze_1 = require("./commands/analyze");
const generate_todos_1 = require("./commands/generate-todos");
const sanitize_1 = require("./commands/sanitize");
const setup_database_1 = require("./commands/setup-database");
const setup_instantdb_1 = require("./commands/setup-instantdb");
const setup_mcp_1 = require("./commands/setup-mcp");
const setup_shadcn_1 = require("./commands/setup-shadcn");
const setup_complete_1 = require("./commands/setup-complete");
const help_1 = require("./commands/help");
const mcp_start_1 = require("./commands/mcp-start");
const tidy_1 = require("./commands/tidy");
const generate_design_prompt_1 = require("./commands/generate-design-prompt");
const generate_sample_data_1 = require("./commands/generate-sample-data");
const generate_screens_1 = require("./commands/generate-screens");
const generate_screens_list_1 = require("./commands/generate-screens-list");
const generate_components_manifest_1 = require("./commands/generate-components-manifest");
const generate_actions_1 = require("./commands/generate-actions");
const generate_assets_1 = require("./commands/generate-assets");
const build_strategy_1 = require("./commands/build-strategy");
const health_check_1 = require("./commands/health-check");
const design_analyze_1 = require("./commands/design-analyze");
const test_1 = require("./commands/test");
const vision_test_1 = require("./commands/vision-test");
const render_1 = require("./commands/render");
const demo_1 = require("./commands/demo");
const plan_1 = require("./commands/plan");
const plan_context_1 = require("./commands/plan-context");
const feature_list_1 = require("./commands/feature-list");
const feature_graph_1 = require("./commands/feature-graph");
const feature_plan_1 = require("./commands/feature-plan");
const feature_validate_1 = require("./commands/feature-validate");
const feature_compile_1 = require("./commands/feature-compile");
const questions_list_1 = require("./commands/questions-list");
const questions_blockers_1 = require("./commands/questions-blockers");
const questions_answer_1 = require("./commands/questions-answer");
const questions_generate_1 = require("./commands/questions-generate");
const questions_validate_1 = require("./commands/questions-validate");
const semantics_extract_1 = require("./commands/semantics-extract");
const semantics_expand_term_1 = require("./commands/semantics-expand-term");
const semantics_validate_1 = require("./commands/semantics-validate");
const semantics_diff_1 = require("./commands/semantics-diff");
const semantics_define_1 = require("./commands/semantics-define");
const impl_plan_1 = require("./commands/impl-plan");
const impl_graph_1 = require("./commands/impl-graph");
const impl_validate_1 = require("./commands/impl-validate");
const impl_batches_1 = require("./commands/impl-batches");
const op_create_file_1 = require("./commands/op-create-file");
const op_patch_file_1 = require("./commands/op-patch-file");
const op_rename_file_1 = require("./commands/op-rename-file");
const op_delete_file_1 = require("./commands/op-delete-file");
const op_add_import_1 = require("./commands/op-add-import");
const op_add_export_1 = require("./commands/op-add-export");
const op_add_classname_1 = require("./commands/op-add-classname");
const op_add_i18n_key_1 = require("./commands/op-add-i18n-key");
const op_add_permission_1 = require("./commands/op-add-permission");
const op_add_test_1 = require("./commands/op-add-test");
const op_add_route_1 = require("./commands/op-add-route");
const op_add_component_1 = require("./commands/op-add-component");
const op_add_action_1 = require("./commands/op-add-action");
const op_add_model_1 = require("./commands/op-add-model");
const op_remove_import_1 = require("./commands/op-remove-import");
const op_list_1 = require("./commands/op-list");
const op_rollback_1 = require("./commands/op-rollback");
const op_batch_1 = require("./commands/op-batch");
const history_1 = require("./commands/history");
const execute_1 = require("./commands/execute");
const validate_watch_1 = require("./commands/validate-watch");
const agent_commands_1 = require("./commands/agent-commands");
// Import sub-agent system
const SubAgentOrchestrator_1 = require("./agents/orchestrator/SubAgentOrchestrator");
const CodeGenSubAgent_1 = require("./agents/implementations/CodeGenSubAgent");
const QASubAgent_1 = require("./agents/implementations/QASubAgent");
const DocsSubAgent_1 = require("./agents/implementations/DocsSubAgent");
const ArchitectAgent_1 = require("./agents/implementations/ArchitectAgent");
const SecurityAgent_1 = require("./agents/implementations/SecurityAgent");
const InteractiveAgent_1 = require("./agents/implementations/InteractiveAgent");
const ProjectSetupAgent_1 = require("./agents/implementations/ProjectSetupAgent");
const WorkflowAgent_1 = require("./agents/implementations/WorkflowAgent");
const PromptConstructorAgent_1 = require("./agents/implementations/PromptConstructorAgent");
const BackendDevAgent_1 = require("./agents/implementations/BackendDevAgent");
const EnhancementAgent_1 = require("./agents/implementations/EnhancementAgent");
const SolverAgent_1 = require("./agents/implementations/SolverAgent");
const TidyAgent_1 = require("./agents/implementations/TidyAgent");
// Register sub-agents with the orchestrator
SubAgentOrchestrator_1.orchestrator.registerAgent(new CodeGenSubAgent_1.CodeGenSubAgent());
SubAgentOrchestrator_1.orchestrator.registerAgent(new QASubAgent_1.QASubAgent());
SubAgentOrchestrator_1.orchestrator.registerAgent(new DocsSubAgent_1.DocsSubAgent());
SubAgentOrchestrator_1.orchestrator.registerAgent(new ArchitectAgent_1.ArchitectAgent());
SubAgentOrchestrator_1.orchestrator.registerAgent(new SecurityAgent_1.SecurityAgent());
SubAgentOrchestrator_1.orchestrator.registerAgent(new InteractiveAgent_1.InteractiveAgent());
SubAgentOrchestrator_1.orchestrator.registerAgent(new ProjectSetupAgent_1.ProjectSetupAgent());
SubAgentOrchestrator_1.orchestrator.registerAgent(new WorkflowAgent_1.WorkflowAgent());
SubAgentOrchestrator_1.orchestrator.registerAgent(new PromptConstructorAgent_1.PromptConstructorAgent());
SubAgentOrchestrator_1.orchestrator.registerAgent(new BackendDevAgent_1.BackendDevAgent());
SubAgentOrchestrator_1.orchestrator.registerAgent(new EnhancementAgent_1.EnhancementAgent());
SubAgentOrchestrator_1.orchestrator.registerAgent(new SolverAgent_1.SolverAgent());
// TidyAgent will initialize AICore lazily when first used
SubAgentOrchestrator_1.orchestrator.registerAgent(new TidyAgent_1.TidyAgent());
const program = new commander_1.Command();
// CLI metadata
program
    .name("mycontext")
    .description("mycontext CLI - AI-powered component generation platform")
    .version(require("../package.json").version)
    .configureOutput({
    writeErr: (str) => process.stderr.write(chalk_1.default.red(str)),
    writeOut: (str) => process.stdout.write(str),
});
// Note: Individual command timeouts are implemented in each command
// to prevent hanging during AI operations
// Global options
program
    .option("-v, --verbose", "enable verbose logging")
    .option("-q, --quiet", "suppress non-essential output")
    .option("--project <name>", "specify project name")
    .option("--yes", "skip all prompts (non-interactive mode)")
    .option("--up", "update the CLI to latest version");
// Initialize command
program
    .command("init [project-name]")
    .description("Initialize a new MyContext project with your preferred framework")
    .option("--description <desc>", "project description")
    .option("--force", "force reinitialization")
    .option("--framework <type>", "framework setup: instantdb (full InstantDB + shadcn setup), nextjs (shadcn + MyContext only), or other (MyContext only). Default: instantdb")
    .option("--with-shadcn", "run shadcn/ui init before MyContext init")
    .option("--scaffold-next", "scaffold a Next.js app (optional)")
    .option("--skip-shadcn", "do not run shadcn/ui init automatically")
    .option("--spec-only", "initialize ONLY context files (skip framework setup)")
    .option("--interactive", "Use recursive clarification loop to build 100% complete ASL specification")
    .option("--preset <id>", "shadcn/ui custom preset ID")
    .option("--preset-agent", "generate design-driven shadcn/ui preset dynamically using browser agent")
    .action(async (projectName, options) => {
    try {
        // If --interactive flag is provided, use the new InitInteractiveCommand
        if (options.interactive) {
            const interactiveCommand = new init_interactive_1.InitInteractiveCommand();
            await interactiveCommand.execute();
        }
        else {
            const initCommand = new init_1.InitCommand();
            await initCommand.execute(projectName, {
                ...program.opts(),
                ...options,
            });
        }
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Init failed:"), error);
        process.exit(1);
    }
});
// Validate command
program
    .command("validate <target>")
    .description("Validate PRD or other context files")
    .option("--file <path>", "specific file to validate")
    .option("--interactive", "interactive validation mode")
    .action(async (target, options) => {
    try {
        const validateCommand = new validate_1.ValidateCommand();
        await validateCommand.execute(target, {
            ...program.opts(),
            ...options,
        });
    }
    catch (error) {
        // soft fail
        if (error instanceof Error && error.message.includes("template")) {
            console.log(chalk_1.default.yellow("⚠️  PRD is a template - please update with your project details first"));
            console.log(chalk_1.default.gray("   Edit: .mycontext/01-prd.md with your project details"));
            console.log(chalk_1.default.gray("   Then run: mycontext generate context --full"));
            process.exit(1);
        }
        // Don't log the error again - it's already been logged by the command
        process.exit(1);
    }
});
// Generate design prompt command
(0, generate_design_prompt_1.registerGenerateDesignPromptCommand)(program);
// MCP commands
const mcpStartCommand = new mcp_start_1.MCPStartCommand();
mcpStartCommand.register(program);
// Generate sample data command
(0, generate_sample_data_1.registerGenerateSampleDataCommand)(program);
// Generate screens command
(0, generate_screens_1.registerGenerateScreensCommand)(program);
// Generate screens list command (extracts screens from user flows)
(0, generate_screens_list_1.registerGenerateScreensListCommand)(program);
// Generate components manifest command (component props and sample data)
(0, generate_components_manifest_1.registerGenerateComponentsManifestCommand)(program);
// Generate actions command (UI-backend action hooks)
(0, generate_actions_1.registerGenerateActionsCommand)(program);
// Generate assets command (planned in ideate)
(0, generate_assets_1.registerGenerateAssetsCommand)(program);
// Test commands (UI flow testing with AI)
(0, test_1.registerTestCommands)(program);
// Vision test commands (AI-powered vision-based testing)
(0, vision_test_1.registerVisionTestCommands)(program);
// Render command (Authority Engine blueprint → media pipeline)
(0, render_1.registerRenderCommand)(program);
// Demo command (universal AI-powered demo recording)
(0, demo_1.registerDemoCommand)(program);
const build_feature_1 = require("./commands/build-feature");
// Plan feature interactively
const planCommand = new plan_1.PlanCommand();
planCommand.register(program);
const planContextCommand = new plan_context_1.PlanContextCommand();
planContextCommand.register(program);
// Build feature from FSR pattern
const buildFeatureCommand = new build_feature_1.BuildFeatureCommand();
buildFeatureCommand.register(program);
// Sub-agent help or other commands can go here
// Context-aware help command
program
    .command("help [topic]")
    .description("Show context-aware help and guidance")
    .option("--verbose", "Show detailed help information")
    .action(async (topic, options) => {
    try {
        const helpCommand = new help_1.HelpCommand(program);
        await helpCommand.execute({
            topic,
            verbose: Boolean(options.verbose),
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Help command failed:"), error);
        process.exit(1);
    }
});
// Refine component command
program
    .command("refine:component <componentName>")
    .description("Refine a specific component with AI suggestions")
    .option("--variant <variant>", "Component variant (mobile/desktop/both)", "both")
    .option("--update-context", "Update context files and regenerate all components")
    .option("--in-place", "Refine only this component file")
    .action(async (componentName, options) => {
    try {
        const { RefineComponentCommand } = await Promise.resolve().then(() => __importStar(require("./commands/refine-component")));
        const refineCommand = new RefineComponentCommand();
        await refineCommand.execute(componentName, options);
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Component refinement failed:"), error);
        process.exit(1);
    }
});
// Generate command (orchestrator for context, types, brand, etc.)
program
    .command("generate [type]")
    .description("Orchestrate the Living Brain (context, types, brand, and more)")
    .option("-f, --full", "Generate full context (PRD + A/B/C/D files)")
    .option("-d, --description <text>", "Project description for generation")
    .option("-c, --context-file <path>", "Context file path")
    .option("-o, --output <dir>", "Output directory")
    .option("--force", "Overwrite existing files")
    .option("--verbose", "Show detailed output")
    .option("--model <name>", "Specific AI model to use")
    .option("--from-schema", "Generate types from InstantDB schema")
    .option("--internal-enrich", "Internal flag for background enrichment")
    .action(async (type, options) => {
    try {
        const { GenerateCommand } = await Promise.resolve().then(() => __importStar(require("./commands/generate")));
        const generateCommand = new GenerateCommand();
        await generateCommand.execute({
            ...program.opts(),
            ...options,
            type,
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Generation failed:"), error);
        process.exit(1);
    }
});
// Compile landing page command
program
    .command("compile-page")
    .description("Orchestrate the Manifest-Driven Landing Page Compilation pipeline")
    .argument("[project-path]", "path to the project directory (defaults to current directory)")
    .option("-b, --benchmark", "enable benchmark mode")
    .option("-o, --output <dir>", "override output directory")
    .option("-v, --verbose", "enable verbose typechecking/healing logs")
    .option("--fresh", "bypass existing stage files and start landing page generation from scratch")
    .action(async (projectPath, options) => {
    try {
        const { CompilePageCommand } = await Promise.resolve().then(() => __importStar(require("./commands/compile-page")));
        const command = new CompilePageCommand();
        await command.execute({
            ...program.opts(),
            ...options,
            project: projectPath, // Pass the positional argument as project option
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Landing page compilation failed:"), error);
        process.exit(1);
    }
});
// Sync README command
program
    .command("sync-readme")
    .description("Synchronize root README.md with MyContext design manifest")
    .option("--verbose", "Show detailed sync information")
    .action(async (options) => {
    try {
        const { SyncREADMECommand } = await Promise.resolve().then(() => __importStar(require("./commands/sync-readme")));
        const syncCommand = new SyncREADMECommand();
        await syncCommand.execute({
            ...program.opts(),
            ...options,
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Sync failed:"), error);
        process.exit(1);
    }
});
// Agent command (Zero-Drift Autonomous Orchestrator)
program
    .command("agent [prompt]")
    .description("Assess a prompt against the Living Brain and propose execution tasks")
    .option("-e, --execute", "Apply the proposed changes to the manifest and PRD")
    .option("-y, --yes", "Skip confirmation prompts")
    .action(async (prompt, options) => {
    try {
        const { AgentCommand } = await Promise.resolve().then(() => __importStar(require("./commands/agent")));
        const agentCommand = new AgentCommand();
        await agentCommand.execute({
            ...program.opts(),
            ...options,
            prompt,
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Agent failed:"), error);
        process.exit(1);
    }
});
// Generate components command
const generateComponentsCmd = program
    .command("generate-components [target]")
    .description("Generate React components using local AI")
    .option("--group <group>", "Component group to generate")
    .option("--all", "Generate all components (alias for target 'all')")
    .option("--core-only", "Generate only the first 10 components for validation")
    .option("--temperature <number>", "Generation temperature (0.1-1.0)", "0.7")
    .option("--max-tokens <number>", "Maximum tokens for generation", "4000")
    .option("--local", "Use local AI generation (no authentication required)")
    .option("--with-tests", "Generate unit tests for each component")
    .option("--final-canvas", "Run a final normalize pass to build the canvas layout")
    .option("--check", "Run typecheck, lint, and tests after generation")
    .option("--verbose", "Show detailed output")
    .option("--debug", "Enable debug logging")
    .action(async (target, options) => {
    try {
        const generateComponentsCommand = new generate_components_1.GenerateComponentsCommand();
        // If --all is provided but no target, use 'all' as target
        // If --core-only is provided, use 'core' as target
        const actualTarget = target || (options.all ? "all" : options.coreOnly ? "core" : undefined);
        if (!actualTarget) {
            console.error(chalk_1.default.red("❌ Please specify a target, use --all flag, or use --core-only flag"));
            process.exit(1);
        }
        await generateComponentsCommand.execute(actualTarget, {
            ...program.opts(),
            ...options,
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Component generation failed:"), error);
        process.exit(1);
    }
});
// Add command
program
    .command("add <component>")
    .description("Add a context-aware component (shadcn or custom)")
    .option("-g, --group <name>", "Component group", "elements")
    .option("--shadcn", "Force shadcn primitive installation")
    .action(async (component, options) => {
    try {
        const { AddCommand } = await Promise.resolve().then(() => __importStar(require("./commands/add")));
        const addCommand = new AddCommand();
        await addCommand.execute(component, options);
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Add failed:"), error);
        process.exit(1);
    }
});
// Ideate command
program
    .command("ideate")
    .description("Generate creative UI/UX concepts based on project context")
    .option("-i, --industry <name>", "Specific industry for ideation")
    .option("-c, --count <number>", "Number of concepts to generate", "3")
    .option("-o, --output <path>", "Output directory for ideas")
    .action(async (options) => {
    try {
        const { IdeateCommand } = await Promise.resolve().then(() => __importStar(require("./commands/ideate")));
        const ideateCommand = new IdeateCommand();
        await ideateCommand.execute({
            industry: options.industry,
            count: parseInt(options.count),
            output: options.output
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Ideation failed:"), error);
        process.exit(1);
    }
});
// Feature Graph commands
program.addCommand(feature_list_1.FeatureListCommand);
program.addCommand(feature_graph_1.FeatureGraphCommand);
program.addCommand(feature_plan_1.FeaturePlanCommand);
program.addCommand(feature_validate_1.FeatureValidateCommand);
program.addCommand(feature_compile_1.FeatureCompileCommand);
// Question Graph commands
program.addCommand(questions_list_1.QuestionsListCommand);
program.addCommand(questions_blockers_1.QuestionsBlockersCommand);
program.addCommand(questions_answer_1.QuestionsAnswerCommand);
program.addCommand(questions_generate_1.QuestionsGenerateCommand);
program.addCommand(questions_validate_1.QuestionsValidateCommand);
// Semantic Dictionary commands
program.addCommand(semantics_extract_1.SemanticsExtractCommand);
program.addCommand(semantics_expand_term_1.SemanticsExpandTermCommand);
program.addCommand(semantics_validate_1.SemanticsValidateCommand);
program.addCommand(semantics_diff_1.SemanticsDiffCommand);
program.addCommand(semantics_define_1.SemanticsDefineCommand);
// Implementation Graph commands
program.addCommand(impl_plan_1.ImplPlanCommand);
program.addCommand(impl_graph_1.ImplGraphCommand);
program.addCommand(impl_validate_1.ImplValidateCommand);
program.addCommand(impl_batches_1.ImplBatchesCommand);
// Validation Daemon (watch mode)
program.addCommand(validate_watch_1.ValidateWatchCommand);
// Atomic Operations commands
program.addCommand(op_create_file_1.OpCreateFileCommand);
program.addCommand(op_patch_file_1.OpPatchFileCommand);
program.addCommand(op_rename_file_1.OpRenameFileCommand);
program.addCommand(op_delete_file_1.OpDeleteFileCommand);
program.addCommand(op_add_import_1.OpAddImportCommand);
program.addCommand(op_add_export_1.OpAddExportCommand);
program.addCommand(op_add_classname_1.OpAddClassnameCommand);
program.addCommand(op_add_i18n_key_1.OpAddI18nKeyCommand);
program.addCommand(op_add_permission_1.OpAddPermissionCommand);
program.addCommand(op_add_test_1.OpAddTestCommand);
program.addCommand(op_add_route_1.OpAddRouteCommand);
program.addCommand(op_add_component_1.OpAddComponentCommand);
program.addCommand(op_add_action_1.OpAddActionCommand);
program.addCommand(op_add_model_1.OpAddModelCommand);
program.addCommand(op_remove_import_1.OpRemoveImportCommand);
program.addCommand(op_list_1.OpListCommand);
program.addCommand(op_rollback_1.OpRollbackCommand);
program.addCommand(op_batch_1.OpBatchCommand);
// History commands
program.addCommand(history_1.HistoryCommand);
program.addCommand(history_1.HistoryListCommand);
program.addCommand(history_1.HistoryExportCommand);
// Execute command (full pipeline)
program.addCommand(execute_1.ExecuteCommand);
// Agent commands
program.addCommand(agent_commands_1.AgentListCommand);
program.addCommand(agent_commands_1.AgentRunCommand);
program.addCommand(agent_commands_1.AgentStatusCommand);
program.addCommand(agent_commands_1.AgentMetricsCommand);
// Build command
program
    .command("build")
    .description("Scaffold the entire application from Living Brain")
    .option("--force", "Force regeneration of all components")
    .action(async (options) => {
    try {
        const { BuildCommand } = await Promise.resolve().then(() => __importStar(require("./commands/build")));
        const buildCommand = new BuildCommand();
        await buildCommand.execute(options);
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Build failed:"), error);
        process.exit(1);
    }
});
// Migrate commands
const migrateCmd = program
    .command("migrate [target]")
    .description("Migrate components or codebase to new standards")
    .option("-c, --component <name>", "Specific component to migrate")
    .option("-g, --group <name>", "Component group to migrate")
    .option("-a, --all", "Migrate all components")
    .option("--no-actions", "Skip actions generation")
    .option("--no-hooks", "Skip hooks generation")
    .option("--no-context", "Skip context generation")
    .option("--no-docs", "Skip docs generation")
    .action(async (target, options) => {
    // If a subcommand was used, target will be the subcommand name
    if (target === "rtl" || target === "radix")
        return;
    try {
        const { MigrateCommand } = await Promise.resolve().then(() => __importStar(require("./commands/migrate")));
        const migrateCommand = new MigrateCommand();
        await migrateCommand.execute(target || "", options);
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Migration failed:"), error);
        process.exit(1);
    }
});
migrateCmd
    .command("rtl")
    .description("Migrate components to RTL-friendly logical properties")
    .option("-p, --path <path>", "Specific file or directory to migrate")
    .option("-a, --all", "Migrate all components in src/components")
    .action(async (options) => {
    try {
        const { MigrateTransformCommand } = await Promise.resolve().then(() => __importStar(require("./commands/migrate-transform")));
        const migrateTransform = new MigrateTransformCommand();
        await migrateTransform.migrateRtl(options);
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ RTL migration failed:"), error);
        process.exit(1);
    }
});
migrateCmd
    .command("radix")
    .description("Refactor components to use Radix/Shadcn primitives")
    .option("-p, --path <path>", "Specific file or directory to migrate")
    .option("-a, --all", "Migrate all components in src/components")
    .action(async (options) => {
    try {
        const { MigrateTransformCommand } = await Promise.resolve().then(() => __importStar(require("./commands/migrate-transform")));
        const migrateTransform = new MigrateTransformCommand();
        await migrateTransform.migrateRadix(options);
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Radix migration failed:"), error);
        process.exit(1);
    }
});
// Registry commands
const registryCmd = program
    .command("registry")
    .description("Manage component registry");
registryCmd
    .command("build")
    .description("Build a registry from the current project components")
    .action(async () => {
    console.log(chalk_1.default.blue("🏗️ Building component registry..."));
    // Placeholder for registry build logic
    console.log(chalk_1.default.green("✅ Registry built at .mycontext/registry.json"));
});
// Design analyze command
program
    .command("design")
    .description("Design system analysis and manifest generation")
    .option("--analyze", "Analyze context files and generate design manifest")
    .option("--validate", "Validate all context files")
    .option("--summary", "Show design manifest summary")
    .option("--regenerate", "Force regenerate design manifest")
    .option("--resume", "Resume from last failed phase")
    .action(async (options) => {
    try {
        const designCommand = new design_analyze_1.DesignAnalyzeCommand();
        await designCommand.execute(options);
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Design analysis failed:"), error);
        process.exit(1);
    }
});
// Feature Assembly command
// Feature Assembly command
// Clone Starter command
// Generate todos command
program
    .command("generate-todos")
    .description("Generate contextual todos from project context")
    .option("-c, --count <number>", "Number of todos to generate", "10")
    .option("-f, --focus <string>", "Focus area for todo generation")
    .option("-e, --energy <level>", "Energy level (low, medium, high)", "medium")
    .option("-x, --complexity <level>", "Complexity level (simple, moderate, complex)", "moderate")
    .option("-p, --project <id>", "Project ID for context")
    .action(async (options) => {
    try {
        const generateTodosCommand = new generate_todos_1.GenerateTodosCommand();
        await generateTodosCommand.generateTodos(options);
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Todo generation failed:"), error);
        process.exit(1);
    }
});
// Setup command
program
    .command("setup")
    .description("Set up MyContext with AI providers and configure for your development stack")
    .option("--force", "Force setup even if already configured")
    .option("--skip-prompts", "Skip interactive prompts")
    .option("--stack <stack>", "Pre-configure for specific stack (nextjs-tailwind-shadcn, react-tailwind-shadcn)")
    .action(async (options) => {
    const setupCommand = new setup_1.SetupCommand();
    await setupCommand.execute(options);
});
// Model commands
// Enhance command
program.addCommand(enhance_1.enhance);
// Refine command
program.addCommand(refine_1.refine);
// Auth command
program
    .command("auth")
    .description("Authenticate with MyContext AI")
    .option("--login", "Login to MyContext AI")
    .option("--logout", "Logout from MyContext AI")
    .option("--status", "Check authentication status")
    .option("--register", "Register new account")
    .action(async (options) => {
    try {
        const authCommand = new auth_1.AuthCommand();
        await authCommand.execute(options);
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Authentication failed:"), error);
        process.exit(1);
    }
});
// Status command
program
    .command("status")
    .description("Check project status and progress")
    .option("--detailed", "show detailed status information")
    .option("--check-health", "perform health checks")
    .action(async (options) => {
    try {
        const statusCommand = new status_1.StatusCommand();
        await statusCommand.execute("", {
            ...program.opts(),
            ...options,
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Status check failed:"), error);
        process.exit(1);
    }
});
// Scan project and assess progress against context.json
program
    .command("scan")
    .description("Scan project structure and assess progress against context.json")
    .option("--assess", "Use AI to assess progress and suggest context merges")
    .option("--json", "Output results as JSON")
    .option("--project <path>", "Project path (defaults to current directory)")
    .action(async (options) => {
    try {
        const { ProjectScanner } = await Promise.resolve().then(() => __importStar(require("./services/ProjectScanner")));
        const projectPath = options.project || process.cwd();
        const scanner = new ProjectScanner(projectPath);
        const snapshot = await scanner.scan();
        scanner.displaySnapshot(snapshot);
        if (options.assess) {
            const brain = await Promise.resolve().then(() => __importStar(require("fs-extra"))).then((fs) => fs.readJson(".mycontext/context.json").catch(() => ({})));
            const report = await scanner.assessProgress(snapshot, brain);
            scanner.displayReport(report);
        }
        if (options.json) {
            console.log(JSON.stringify(snapshot, null, 2));
        }
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Scan failed:"), error);
        process.exit(1);
    }
});
// Registry: Update command — rebuild file-registry.json from disk scan
program
    .command("registry:update")
    .description("Build/update the file registry (.mycontext/file-registry.json) by scanning the project")
    .option("--project <path>", "Project path (defaults to current directory)")
    .action(async (options) => {
    try {
        const { RegistryBuilder } = await Promise.resolve().then(() => __importStar(require("./services/RegistryBuilder")));
        const projectPath = options.project || process.cwd();
        const builder = new RegistryBuilder(projectPath);
        console.log(chalk_1.default.cyan("🔍 Scanning project files..."));
        const registry = await builder.build();
        await builder.write(registry);
        const total = Object.keys(registry.files).length;
        const tracked = Object.values(registry.files).filter((f) => f.status === "tracked").length;
        const untracked = Object.values(registry.files).filter((f) => f.status === "untracked").length;
        console.log(chalk_1.default.green(`✓ File registry updated: ${total} files (${tracked} tracked, ${untracked} untracked, ${total - tracked - untracked} ignored)`));
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Registry update failed:"), error);
        process.exit(1);
    }
});
// Registry: Diff command — compare registry against current file system
program
    .command("registry:diff")
    .description("Compare file-registry.json against the current file system to detect drift")
    .option("--project <path>", "Project path (defaults to current directory)")
    .option("--strict", "Exit with error code if untracked files exist")
    .option("--json", "Output results as JSON")
    .action(async (options) => {
    try {
        const { RegistryDiffEngine } = await Promise.resolve().then(() => __importStar(require("./services/RegistryDiffEngine")));
        const projectPath = options.project || process.cwd();
        const engine = new RegistryDiffEngine(projectPath);
        const report = await engine.diff();
        if (options.json) {
            console.log(JSON.stringify(report, null, 2));
        }
        else {
            engine.displayReport(report);
        }
        if (options.strict && report.hasUntrackedFiles) {
            process.exit(1);
        }
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Registry diff failed:"), error);
        process.exit(1);
    }
});
// Update command (mycontext update)
program
    .command("update")
    .description("Update mycontext CLI to the latest version")
    .action(async () => {
    try {
        const updater = new update_1.UpdateCommand();
        await updater.execute();
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Update failed:"), error);
        process.exit(1);
    }
});
// Clean command
program
    .command("clean")
    .description("Clean and repair malformed context files")
    .option("--project <path>", "Project path (defaults to current directory)")
    .action(async (options) => {
    try {
        await (0, clean_1.runCleanCommand)(options.project);
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Clean failed:"), error.message);
        process.exit(1);
    }
});
// Add build strategy command
program.addCommand(build_strategy_1.buildStrategyCommand);
// Health check command
const healthCheckCommand = new health_check_1.HealthCheckCommand();
healthCheckCommand.register(program);
// Doctor command (project diagnostics & auto-fix)
const { DoctorCommand } = require("./commands/doctor");
const doctorCommand = new DoctorCommand();
doctorCommand.register(program);
// Tidy command
const tidyCommand = new tidy_1.TidyCommand();
tidyCommand.register(program);
// TUI dream cockpit command
program
    .command("tui")
    .description("Launch the MyContext dream cockpit")
    .action(async () => {
    const { TUIClient } = await Promise.resolve().then(() => __importStar(require("./tui/TUIClient")));
    const tui = new TUIClient();
    await tui.start();
});
// Blueprint command
const { BlueprintCommand } = require("./commands/blueprint");
const blueprintCommand = new BlueprintCommand();
blueprintCommand.register(program);
// Analyze command for existing projects
program
    .command("analyze")
    .description("Analyze existing project and generate context files")
    .option("--output <dir>", "Output directory for context files", ".mycontext")
    .option("--generate-context", "Generate context files", true)
    .option("--include-brand", "Include brand analysis", true)
    .option("--include-types", "Include type analysis", true)
    .option("--include-components", "Include component analysis", true)
    .option("--image <path>", "Analyze an image (screenshot/mockup) instead of the codebase")
    .option("--verbose", "Verbose output")
    .action(async (options) => {
    try {
        const command = new analyze_1.AnalyzeCommand();
        await command.execute(".", {
            output: options.output,
            generateContext: Boolean(options.generateContext),
            includeBrand: Boolean(options.includeBrand),
            includeTypes: Boolean(options.includeTypes),
            includeComponents: Boolean(options.includeComponents),
            verbose: Boolean(options.verbose),
            image: options.image, // Pass image option
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Analysis failed:"), error);
        process.exit(1);
    }
});
// Sanitize command for cleaning up project
program
    .command("sanitize")
    .description("Sanitize project by checking for redundancy, duplicates, and unreachable code")
    .option("--fix", "Automatically fix issues where possible")
    .option("--verbose", "Verbose output")
    .option("--no-duplicates", "Skip duplicate file checking")
    .option("--no-unreachable", "Skip unreachable code checking")
    .option("--no-redundancy", "Skip redundant file checking")
    .option("--no-unused", "Skip unused file checking")
    .action(async (options) => {
    try {
        const command = new sanitize_1.SanitizeCommand();
        await command.execute(".", {
            fix: Boolean(options.fix),
            verbose: Boolean(options.verbose),
            checkDuplicates: options.duplicates !== false,
            checkUnreachable: options.unreachable !== false,
            checkRedundancy: options.redundancy !== false,
            checkUnused: options.unused !== false,
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Sanitization failed:"), error);
        process.exit(1);
    }
});
// Database setup command
program
    .command("setup-database")
    .description("Set up database and authentication (InstantDB, Supabase, Firebase)")
    .option("--provider <provider>", "Database provider", "instantdb")
    .option("--no-auth", "Skip authentication setup")
    .option("--no-schema", "Skip schema generation")
    .option("--no-components", "Skip component generation")
    .action(async (options) => {
    try {
        const command = new setup_database_1.DatabaseSetupCommand();
        await command.execute({
            provider: options.provider,
            auth: options.auth !== false,
            schema: options.schema !== false,
            components: options.components !== false,
            skipAuth: options.auth === false,
            skipSchema: options.schema === false,
            skipComponents: options.components === false,
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Database setup failed:"), error);
        process.exit(1);
    }
});
// InstantDB + MCP setup command
program
    .command("setup-instantdb")
    .description("Set up InstantDB with MCP integration for real-time database and AI-powered development")
    .option("--no-mcp", "Skip MCP integration setup")
    .option("--no-auth", "Skip authentication setup")
    .option("--no-schema", "Skip schema generation")
    .option("--no-components", "Skip component generation")
    .option("--app-id <id>", "InstantDB App ID")
    .option("--token <token>", "InstantDB Personal Access Token")
    .action(async (options) => {
    try {
        const command = new setup_instantdb_1.InstantDBSetupCommand();
        await command.execute({
            mcp: options.mcp !== false,
            auth: options.auth !== false,
            schema: options.schema !== false,
            components: options.components !== false,
            skipAuth: options.auth === false,
            skipSchema: options.schema === false,
            skipComponents: options.components === false,
            appId: options.appId,
            token: options.token,
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ InstantDB setup failed:"), error);
        process.exit(1);
    }
});
// MCP setup command
program
    .command("setup-mcp")
    .description("Set up MCP (Model Context Protocol) for AI-powered development with various providers")
    .option("--provider <provider>", "MCP provider (instantdb, github, custom)", "instantdb")
    .option("--server <url>", "Custom MCP server URL")
    .option("--token <token>", "Provider token")
    .option("--config <path>", "Custom MCP configuration file")
    .option("--no-install", "Skip dependency installation")
    .action(async (options) => {
    try {
        const command = new setup_mcp_1.MCPSetupCommand();
        await command.execute({
            provider: options.provider,
            server: options.server,
            token: options.token,
            config: options.config,
            install: options.install !== false,
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ MCP setup failed:"), error);
        process.exit(1);
    }
});
// shadcn/ui setup command
program
    .command("setup-shadcn")
    .description("Set up shadcn/ui components with interactive terminal installation")
    .option("--all", "Install all essential components automatically")
    .option("--components <list>", "Comma-separated list of components to install")
    .option("--force", "Force reinitialization even if already set up")
    .option("--skip-prompts", "Skip interactive prompts")
    .option("-p, --preset <id>", "shadcn/ui custom preset ID")
    .option("--preset-agent", "generate design-driven shadcn/ui preset dynamically using browser agent")
    .action(async (options) => {
    try {
        const command = new setup_shadcn_1.SetupShadcnCommand();
        await command.execute({
            all: Boolean(options.all),
            components: options.components
                ? options.components.split(",").map((c) => c.trim())
                : undefined,
            force: Boolean(options.force),
            skipPrompts: Boolean(options.skipPrompts),
            preset: options.preset,
            presetAgent: Boolean(options.presetAgent),
        });
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ shadcn/ui setup failed:"), error);
        process.exit(1);
    }
});
// Setup complete command - guided complete project setup
const setupCompleteCommand = new setup_complete_1.SetupCompleteCommand();
setupCompleteCommand.register(program);
// Help command
program
    .command("help")
    .description("Show detailed help information")
    .action(() => {
    console.log(chalk_1.default.blue.bold("🚀 MyContext CLI - Agent-Driven Development\n"));
    console.log(chalk_1.default.yellow("Quick Start:"));
    console.log(chalk_1.default.gray("  # Initialize with your preferred framework"));
    console.log(chalk_1.default.cyan("  mycontext init my-project --framework instantdb"));
    console.log(chalk_1.default.gray("  # Options: instantdb (default) | nextjs | other\n"));
    console.log(chalk_1.default.gray("  # Set API key (Gemini FREE recommended)"));
    console.log(chalk_1.default.cyan("  echo 'GEMINI_API_KEY=your-key' > .mycontext/.env"));
    console.log(chalk_1.default.gray("  mycontext generate context --full --description 'Your project'"));
    console.log(chalk_1.default.gray("  generate <type>         - Generate context files"));
    console.log(chalk_1.default.gray("  generate <type>         - Generate context files"));
    console.log(chalk_1.default.gray("  generate-components <target> - Generate React components"));
    console.log(chalk_1.default.gray("  enhance <target>        - Enhance components with AI"));
    console.log(chalk_1.default.gray("  refine <component>      - Refine components with AI"));
    console.log(chalk_1.default.gray("  setup-instantdb         - Set up InstantDB with MCP integration"), chalk_1.default.gray("  setup-mcp               - Set up MCP (Model Context Protocol)"));
    console.log(chalk_1.default.gray("  setup-database          - Set up database and authentication"));
    console.log(chalk_1.default.gray("  auth                    - Authenticate with MyContext AI"));
    console.log(chalk_1.default.gray("  auth --login            - Login to MyContext AI"));
    console.log(chalk_1.default.gray("  auth --logout           - Logout from MyContext AI"));
    console.log(chalk_1.default.gray("  auth --status           - Check authentication status"));
    console.log(chalk_1.default.gray("  auth --register         - Register new account"));
    console.log(chalk_1.default.yellow("Generation Commands:"));
    console.log(chalk_1.default.gray("  generate context        - Generate PRD and user stories"));
    console.log(chalk_1.default.gray("  generate types          - Generate TypeScript types"));
    console.log(chalk_1.default.gray("  generate brand          - Generate branding guidelines"));
    console.log(chalk_1.default.gray("  generate components-list - Generate component list"));
    console.log(chalk_1.default.gray("  generate:design-prompt  - Generate prompt for AI design tools"));
    console.log(chalk_1.default.gray("  generate:sample-data    - Generate realistic test data"));
    console.log(chalk_1.default.gray("  generate:screens        - Generate visual screens (HTML/PNG)"));
    console.log(chalk_1.default.gray("  app-structure           - Generate app structure\n"));
    console.log(chalk_1.default.yellow("List Types:"));
    console.log(chalk_1.default.gray("  components              - List generated components"));
    console.log(chalk_1.default.gray("  projects                - List project information"));
    console.log(chalk_1.default.gray("  files                   - List context files"));
    console.log(chalk_1.default.gray("  all                     - List everything\n"));
    console.log(chalk_1.default.yellow("Examples:"));
    console.log(chalk_1.default.cyan("  # Framework initialization"));
    console.log(chalk_1.default.gray("  mycontext init my-app --framework instantdb  # Full stack"));
    console.log(chalk_1.default.gray("  mycontext init my-app --framework nextjs     # Next.js + shadcn"));
    console.log(chalk_1.default.gray("  mycontext init my-app --framework other      # MyContext only\n"));
    console.log(chalk_1.default.cyan("  # With description"));
    console.log(chalk_1.default.gray('  mycontext init todo-app --description "A simple todo application"'));
    console.log(chalk_1.default.gray('  mycontext init clarity-app --framework instantdb --description "A Clarity app"\n'));
    console.log(chalk_1.default.cyan("  # Screenshot analysis"));
    console.log(chalk_1.default.gray("  mycontext analyze mockup.png  # Gemini Vision analysis"));
    console.log(chalk_1.default.gray("  mycontext analyze --generate-context  # Analyze and generate context\n"));
    console.log(chalk_1.default.cyan("  # Context generation"));
    console.log(chalk_1.default.gray("  mycontext generate context --full"));
    console.log(chalk_1.default.gray("  mycontext generate:sample-data --count 20"));
    console.log(chalk_1.default.gray("  mycontext generate:screens --all"));
    console.log(chalk_1.default.gray("  mycontext generate:screens login"));
    console.log(chalk_1.default.gray("  mycontext generate:design-prompt --format stitch"));
    console.log(chalk_1.default.gray("  mycontext validate prd --interactive"));
    console.log(chalk_1.default.gray("  mycontext generate-components authentication"));
    console.log(chalk_1.default.gray("  mycontext generate-components all"));
    console.log(chalk_1.default.gray("  mycontext enhance TodoApp.tsx --prompt 'Make it modern'"));
    console.log(chalk_1.default.gray("  mycontext enhance forms-input --yes"));
    console.log(chalk_1.default.gray("  mycontext refine Button.tsx --prompt 'Add accessibility'"));
    console.log(chalk_1.default.gray("  mycontext refine Card.tsx --output-format diff --interactive"));
    console.log(chalk_1.default.gray("  mycontext status --check-health"));
    console.log(chalk_1.default.yellow("Documentation:"));
    console.log(chalk_1.default.gray("  https://mycontext.fbien.com/docs\n"));
});
// Default action
program.action(async () => {
    // If --up is provided without a subcommand, run update
    const opts = program.opts();
    if (opts.up) {
        const updater = new update_1.UpdateCommand();
        await updater.execute();
        process.exit(0);
    }
    // Check if we should launch TUI
    const { TUIClient } = await Promise.resolve().then(() => __importStar(require("./tui/TUIClient")));
    const tui = new TUIClient();
    await tui.start();
});
// Parse command line arguments
program
    .parseAsync()
    .then(() => {
    // Note: TUI handles its own exit
    if (program.args.length > 0)
        process.exit(0);
})
    .catch((error) => {
    console.error(chalk_1.default.red("❌ Command failed:"), error.message);
    process.exit(1);
});
//# sourceMappingURL=cli.js.map