#!/usr/bin/env node
"use strict";
/**
 * TUI subcommand for dominds CLI
 *
 * Usage:
 *   dominds tui [options] <taskdoc-path> [prompts...]
 *   dominds run [options] <taskdoc-path> [prompts...]
 *
 * Options:
 *   -m, --member <id>: Specify team member ID to use as agent
 *   -i, --id <dialog-id>: Resume existing dialog or use custom dialog ID
 *   --list: List all dialogs (running, completed, archived)
 *   --help: Show help message
 *   -p, --print-only: Non-interactive mode (for automated testing)
 *   --version: Show version information
 */
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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.main = main;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const log_1 = require("../log");
const process_title_1 = require("../process-title");
// Helper function to get package version
function getPackageVersion() {
    try {
        const packagePath = path.join(__dirname, '../package.json');
        const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
        return packageJson.version || 'unknown';
    }
    catch (error) {
        return 'unknown';
    }
}
function showVersion() {
    console.log(`dominds v${getPackageVersion()}`);
}
function showHelp() {
    console.log(`dominds v${getPackageVersion()}`);
    console.log('');
    console.log('Usage: dominds tui [options] [taskdoc] [prompt]');
    console.log('       dominds run [options] [taskdoc] [prompt]');
    console.log('');
    console.log('Start or continue a dialog with an AI team member using a Taskdoc.');
    console.log('');
    console.log("Note: rtws (runtime workspace) directory is `process.cwd()`. Use 'dominds -C <dir> tui ...' to run in another rtws.");
    console.log('');
    console.log('Arguments:');
    console.log('  <taskdoc-path>    Path to Taskdoc (required for dialog)');
    console.log('  [prompts...]      Optional initial prompts');
    console.log('');
    console.log('Options:');
    console.log('  -m <member>            Specify team member');
    console.log('  -i <dialog-id>         Resume dialog with specified ID');
    console.log('  -p, --print-only       Non-interactive mode (for automated testing)');
    console.log('  --list                 List all dialogs');
    console.log('  --version              Show version information');
    console.log('  --help                 Show this help message');
    console.log('');
    console.log('Examples:');
    console.log('  dominds tui task.tsk "implement feature"');
    console.log('  dominds tui -i abc123');
    console.log('  dominds tui --list');
    console.log('  dominds tui --version');
    console.log('');
    console.log('Note: All bare arguments (without -- prefix) are treated as Taskdocs');
    console.log('      or prompts, ensuring no conflicts with user files.');
}
function parseArgs(argv) {
    const out = { prompts: [] };
    let inOptions = true;
    let taskDocPathSet = false;
    for (let i = 0; i < argv.length; i++) {
        const a = argv[i];
        if (inOptions) {
            if (a === '--') {
                inOptions = false;
                continue;
            }
            if (a === '-m' || a === '--member') {
                const next = argv[i + 1];
                if (next == null) {
                    throw new Error(`${a} requires a team member ID argument`);
                }
                out.member = next;
                i++;
                continue;
            }
            if (a === '-i' || a === '--id') {
                const next = argv[i + 1];
                if (next == null) {
                    throw new Error(`${a} requires a dialog ID argument`);
                }
                out.dialogId = next;
                i++;
                continue;
            }
            if (a === '--list') {
                out.list = true;
                continue;
            }
            if (a === '--version') {
                out.version = true;
                continue;
            }
            if (a === '--help' || a === '-h') {
                out.help = true;
                continue;
            }
            if (a === '-p' || a === '--print-only') {
                out.nonInteractive = true;
                continue;
            }
            if (a.startsWith('-')) {
                throw new Error(`Unknown option: ${a}`);
            }
            // Check for invalid commands that look like commands but aren't recognized
            if (a.includes('-') && !a.includes('.') && !a.includes('/')) {
                throw new Error(`Unknown command: ${a}. Use --help to see available commands.`);
            }
            // First non-option token is mandatory taskDocPath
            if (!taskDocPathSet) {
                out.taskDocPath = a;
                taskDocPathSet = true;
                continue;
            }
            // Subsequent non-option tokens before -- count as prompts
            out.prompts.push(a);
            continue;
        }
        // After --, treat everything as prompt fragments (including dash-started)
        out.prompts.push(a);
    }
    return out;
}
async function main(argv = process.argv.slice(2)) {
    try {
        (0, process_title_1.setRtwsProcessTitle)();
        const args = parseArgs(argv);
        // Handle version flag
        if (args.version) {
            showVersion();
            return;
        }
        // Handle help flag
        if (args.help) {
            showHelp();
            return;
        }
        if (args.taskDocPath && !args.list) {
            const normalized = args.taskDocPath.replace(/\\/g, '/').replace(/\/+$/g, '');
            if (!normalized.endsWith('.tsk')) {
                throw new Error(`taskdoc-path must be a Taskdoc directory ending in '.tsk' (got: '${args.taskDocPath}')`);
            }
        }
        console.log(`Dominds TUI not implemented yet.`);
    }
    catch (error) {
        console.error('Error:', error instanceof Error ? error.message : String(error));
        process.exit(1);
    }
}
if (require.main === module) {
    main().catch((error) => {
        log_1.log.error('CLI execution failed', error);
        process.exit(1);
    });
}
