"use strict";
/**
 * Rule Command Handler
 *
 * Manage folder-to-profile routing rules stored under `rules:` in
 * ~/.ccs/config.yaml. These rules drive the generated claude() shell wrapper,
 * which auto-selects a profile based on the directory Claude is launched from.
 *
 *   ccs rule add <profile> [path]   Route a folder (and subfolders) to a profile
 *   ccs rule remove [path]          Remove the rule for a folder
 *   ccs rule list                   Show all rules
 *
 * [path] defaults to the current directory. Matching is "longest path wins".
 */
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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleRuleCommand = void 0;
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const ui_1 = require("../utils/ui");
const named_command_router_1 = require("./named-command-router");
const unified_config_loader_1 = require("../config/unified-config-loader");
const rules_1 = require("../config/schemas/rules");
const HELP_TOKENS = ['--help', '-h'];
function wantsHelp(args) {
    return args.some((arg) => HELP_TOKENS.includes(arg));
}
function positionals(args) {
    return args.filter((arg) => !arg.startsWith('-'));
}
/** Expand a leading ~ to the user's home directory. */
function expandHome(input) {
    if (input === '~') {
        return os.homedir();
    }
    if (input.startsWith('~/')) {
        return path.join(os.homedir(), input.slice(2));
    }
    return input;
}
/** Resolve a rule path argument to an absolute, normalized path (defaults to cwd). */
function resolveRulePath(input) {
    const raw = input && input.trim().length > 0 ? input.trim() : process.cwd();
    return path.resolve(expandHome(raw));
}
async function handleAdd(args) {
    await (0, ui_1.initUI)();
    if (wantsHelp(args)) {
        await showHelp();
        return;
    }
    const pos = positionals(args);
    const profile = pos[0];
    if (!profile) {
        console.log((0, ui_1.warn)('Missing profile name'));
        console.log('');
        console.log('Usage: ccs rule add <profile> [path]');
        process.exit(1);
    }
    const rulePath = resolveRulePath(pos[1]);
    let existed = false;
    (0, unified_config_loader_1.mutateUnifiedConfig)((config) => {
        const rules = config.rules ? [...config.rules] : [];
        const index = rules.findIndex((rule) => rule.path === rulePath);
        if (index >= 0) {
            existed = true;
            rules[index] = { path: rulePath, profile };
        }
        else {
            rules.push({ path: rulePath, profile });
        }
        config.rules = rules;
    });
    console.log((0, ui_1.ok)(`${existed ? 'Updated' : 'Added'} rule: ${rulePath} -> ${profile}`));
}
async function handleRemove(args) {
    await (0, ui_1.initUI)();
    if (wantsHelp(args)) {
        await showHelp();
        return;
    }
    const rulePath = resolveRulePath(positionals(args)[0]);
    let removed = false;
    (0, unified_config_loader_1.mutateUnifiedConfig)((config) => {
        const rules = config.rules ? [...config.rules] : [];
        const index = rules.findIndex((rule) => rule.path === rulePath);
        if (index >= 0) {
            rules.splice(index, 1);
            removed = true;
            config.rules = rules.length > 0 ? rules : undefined;
        }
    });
    if (removed) {
        console.log((0, ui_1.ok)(`Removed rule for: ${rulePath}`));
    }
    else {
        console.log((0, ui_1.warn)(`No rule found for: ${rulePath}`));
    }
}
async function handleList() {
    await (0, ui_1.initUI)();
    const config = (0, unified_config_loader_1.loadOrCreateUnifiedConfig)();
    const rules = config.rules ?? [];
    console.log('');
    console.log((0, ui_1.header)('Folder Routing Rules'));
    console.log('');
    if (rules.length === 0) {
        console.log((0, ui_1.info)('No rules configured'));
        console.log('');
        console.log('Add one with: ccs rule add <profile> [path]');
        return;
    }
    const winner = (0, rules_1.matchFolderRule)(rules, process.cwd());
    // Sort longest path first so the listing mirrors match precedence.
    const sorted = [...rules].sort((a, b) => b.path.length - a.path.length || a.path.localeCompare(b.path));
    const profileWidth = Math.max(...sorted.map((rule) => rule.profile.length));
    for (const rule of sorted) {
        const isWinner = winner?.path === rule.path && winner?.profile === rule.profile;
        const marker = isWinner ? '*' : ' ';
        const suffix = isWinner ? '  (matches current directory)' : '';
        console.log(`  ${marker} ${rule.profile.padEnd(profileWidth)}  ${rule.path}${suffix}`);
    }
    console.log('');
    console.log((0, ui_1.info)(`${rules.length} rule${rules.length === 1 ? '' : 's'} configured`));
}
async function showHelp() {
    await (0, ui_1.initUI)();
    console.log('');
    console.log((0, ui_1.header)('ccs rule - Folder-to-profile routing'));
    console.log('');
    console.log('Usage: ccs rule <command> [options]');
    console.log('');
    console.log('Commands:');
    console.log('  add <profile> [path]   Route a folder (and its subfolders) to a profile');
    console.log('  remove [path]          Remove the rule for a folder');
    console.log('  list                   Show all routing rules');
    console.log('');
    console.log('Notes:');
    console.log('  - [path] defaults to the current directory when omitted.');
    console.log('  - Most specific (longest) matching path wins; no match runs plain claude.');
    console.log('  - The claude() shell wrapper uses these rules to auto-select a profile.');
    console.log('');
    console.log('Examples:');
    console.log('  ccs rule add glm                 Route the current folder to "glm"');
    console.log('  ccs rule add kimi ~/work/secret  Route a specific folder to "kimi"');
    console.log('  ccs rule remove                  Remove the current folder rule');
    console.log('  ccs rule list                    List all rules');
    console.log('');
}
const RULE_ROUTES = [
    { name: 'add', handle: handleAdd },
    { name: 'remove', aliases: ['rm', 'delete'], handle: handleRemove },
    { name: 'list', aliases: ['ls'], handle: () => handleList() },
];
async function handleRuleCommand(args) {
    await (0, named_command_router_1.dispatchNamedCommand)({
        args,
        routes: RULE_ROUTES,
        onHelp: showHelp,
        allowEmptyHelp: true,
        onUnknown: async (command) => {
            await (0, ui_1.initUI)();
            console.log((0, ui_1.warn)(`Unknown rule command: ${command}`));
            await showHelp();
            process.exit(1);
        },
    });
}
exports.handleRuleCommand = handleRuleCommand;
//# sourceMappingURL=rule-command.js.map