/**
 * olam install — pick an archetype and record it locally.
 *
 *   olam install --as=<archetype> [--capability <name>]... [--force]
 *
 * Archetype-aware setup for Olam. Writes `~/.olam/role.yaml` with the
 * resolved archetype and capability set so later commands + MCP
 * surfaces can introspect what this install is allowed to do.
 *
 * Local behaviour is intentionally minimal — this command records
 * intent and prints archetype-specific next steps. Heavy lifting
 * (docker bootstrap, auth container, CF deploy) stays in its
 * dedicated commands (`olam auth up`, `wrangler deploy`) so
 * `olam install` remains idempotent and boring.
 *
 * Authz enforcement is NOT wired into this file. Local mode is
 * single-actor by design; CF enforcement lands in a later slice that
 * stores roles server-side in OLAM_ROLES KV.
 */
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import pc from 'picocolors';
import { stringify as stringifyYaml } from 'yaml';
import { ARCHETYPES, UnknownArchetypeError, assertCapability, expandArchetype, getArchetype, listArchetypeNames, } from '@olam/core/src/archetypes/index.js';
import { printError, printHeader, printInfo, printSuccess } from '../output.js';
const ROLE_FILE_PATH = path.join(os.homedir(), '.olam', 'role.yaml');
function readRoleFile() {
    if (!fs.existsSync(ROLE_FILE_PATH))
        return null;
    try {
        // Lazy import so the CLI can still run if yaml is somehow missing
        // (it's already a peer dep via core, but defensive).
        const raw = fs.readFileSync(ROLE_FILE_PATH, 'utf-8');
        // The file is structurally simple; parseYaml would work too but
        // we keep the install command dependency-light.
        const m = /archetype:\s*(\S+)/.exec(raw);
        if (!m)
            return null;
        const archetype = m[1];
        const customCapabilities = [];
        for (const line of raw.split('\n')) {
            const caps = /^\s+-\s+(\S+)$/.exec(line);
            if (caps)
                customCapabilities.push(caps[1]);
        }
        const installedAtMatch = /installedAt:\s*(\d+)/.exec(raw);
        return {
            archetype,
            customCapabilities,
            installedAt: installedAtMatch ? Number(installedAtMatch[1]) : 0,
        };
    }
    catch {
        return null;
    }
}
function writeRoleFile(role) {
    fs.mkdirSync(path.dirname(ROLE_FILE_PATH), { recursive: true });
    const yaml = stringifyYaml({
        archetype: role.archetype,
        customCapabilities: [...role.customCapabilities],
        installedAt: role.installedAt,
    });
    fs.writeFileSync(ROLE_FILE_PATH, yaml, { mode: 0o644 });
}
/** Per-archetype "what this install covers / what to do next" hints. */
function nextStepsFor(archetype) {
    switch (archetype) {
        case 'user':
            return [
                'You can now run `olam create --task "..."` against a workspace your admin has curated.',
                'Register the Claude Code plugin if you haven\'t: `claude plugin install ./plugin`.',
            ];
        case 'workspace-curator':
            return [
                'You can now curate the catalog: `olam workspace add <name> --from-config`.',
                'Share workspace YAML files via your usual dotfiles / rsync flow.',
            ];
        case 'policy-admin':
            return [
                'Set deployment-wide policy via env vars (OLAM_CLAUDE_PERMISSION_MODE) or wrangler secrets.',
                'PR-gate defaults can be overridden per-workspace under `policy.set`.',
            ];
        case 'bootstrapper':
            return [
                'Start the auth container: `olam services up`, then `olam auth login`.',
                'For Cloudflare deployments: `cd packages/cloudflare-worker && pnpm wrangler deploy`.',
            ];
        case 'admin':
            return [
                'Start the auth container: `olam services up`, then `olam auth login`.',
                'Curate workspaces: `olam workspace add <name> --from-config`.',
                'Assign narrower archetypes to teammates (CF side, once slice C lands): use `role.manage`.',
            ];
        case 'dev':
            return [
                'You have repo-local privileges. Run `npm run build:ci && npm run test:ci`.',
                'Everything an admin has is available.',
            ];
        default:
            return [];
    }
}
export function registerInstall(program) {
    program
        .command('install')
        .description('Pick an archetype preset for this Olam install')
        .option('--as <archetype>', 'Archetype name (user, workspace-curator, policy-admin, bootstrapper, admin, dev)')
        .option('--capability <name>', 'Additional capability to grant beyond the archetype preset (repeatable)', (value, acc) => {
        acc.push(value);
        return acc;
    }, [])
        .option('--force', 'Overwrite an existing role.yaml', false)
        .option('--show', 'Print the current install\'s archetype and exit', false)
        .action((opts) => {
        if (opts.show) {
            const existing = readRoleFile();
            if (!existing) {
                console.log(pc.dim(`No install recorded at ${ROLE_FILE_PATH}`));
                return;
            }
            printHeader('Current install');
            printInfo('Archetype', existing.archetype);
            printInfo('File', ROLE_FILE_PATH);
            const caps = expandArchetype(existing.archetype);
            for (const cap of existing.customCapabilities)
                caps.add(cap);
            printHeader(`Effective capabilities (${caps.size})`);
            for (const cap of [...caps].sort()) {
                console.log(`  ${cap}`);
            }
            return;
        }
        if (!opts.as) {
            printError('Missing --as <archetype>. Known archetypes:');
            for (const arch of ARCHETYPES) {
                console.log(`  ${pc.bold(arch.name.padEnd(20))} ${pc.dim(arch.description)}`);
            }
            process.exitCode = 1;
            return;
        }
        const archetype = getArchetype(opts.as);
        if (!archetype) {
            printError(`Unknown archetype "${opts.as}". Known: ${listArchetypeNames().join(', ')}`);
            process.exitCode = 1;
            return;
        }
        // Validate any additional capabilities up front so we don't
        // half-write a role file with a typo'd capability.
        const extras = [];
        for (const raw of opts.capability) {
            try {
                extras.push(assertCapability(raw));
            }
            catch (err) {
                printError(err instanceof Error ? err.message : String(err));
                process.exitCode = 1;
                return;
            }
        }
        const existing = readRoleFile();
        if (existing && !opts.force) {
            printError(`Install already recorded as "${existing.archetype}" at ${ROLE_FILE_PATH}. Pass --force to overwrite.`);
            process.exitCode = 1;
            return;
        }
        let resolved;
        try {
            resolved = expandArchetype(archetype.name);
        }
        catch (err) {
            if (err instanceof UnknownArchetypeError) {
                printError(err.message);
                process.exitCode = 1;
                return;
            }
            throw err;
        }
        for (const extra of extras)
            resolved.add(extra);
        writeRoleFile({
            archetype: archetype.name,
            customCapabilities: extras,
            installedAt: Date.now(),
        });
        printHeader(`Installed as ${pc.bold(archetype.name)}`);
        printInfo('File', ROLE_FILE_PATH);
        printInfo('Description', archetype.description);
        printInfo('Capabilities', `${resolved.size} total`);
        if (extras.length > 0) {
            printInfo('Added beyond preset', extras.join(', '));
        }
        const steps = nextStepsFor(archetype.name);
        if (steps.length > 0) {
            printHeader('Next steps');
            for (const step of steps)
                console.log(`  ${pc.dim('•')} ${step}`);
        }
        printSuccess('Done. Run `olam install --show` to see the full capability list.');
    });
}
//# sourceMappingURL=install.js.map