import { mkdir, readlink, lstat, unlink, symlink } from 'node:fs/promises';
import { join } from 'node:path';
import { getPackageRoot } from './package-root.js';
import { getClaudeSkillsDir, getTeTrackingDir, getCodexSkillsDir, isCodexInstalled } from './home.js';
import { t } from '../i18n/translate.js';
const SKILL_NAMES = ['generate-tracking-plan', 'generate-tracking-code', 'data-integration-helper'];
const CLAUDE_MD = 'CLAUDE.md';
const AGENTS_MD = 'AGENTS.md';
async function linkTarget(path) {
    try {
        const s = await lstat(path);
        if (!s.isSymbolicLink())
            return 'NOT_SYMLINK';
        return await readlink(path);
    }
    catch {
        return null;
    }
}
async function linkSkill(name, src, dst, opts, report, label) {
    const t = await linkTarget(dst);
    if (opts.uninstall) {
        if (t === src) {
            await unlink(dst);
            report.uninstalled.push(`${name} (${label})`);
        }
        return;
    }
    if (t === src) {
        report.skipped.push(`${name} (${label})`);
        return;
    }
    if (t === null) {
        await symlink(src, dst, 'dir');
        report.installed.push(`${name} (${label})`);
        return;
    }
    if (opts.force && t !== 'NOT_SYMLINK') {
        await unlink(dst);
        await symlink(src, dst, 'dir');
        report.installed.push(`${name} (${label})`);
    }
    else {
        report.conflicts.push(`${name} (${label})`);
    }
}
export async function runInit(opts = {}) {
    const pkg = getPackageRoot();
    const skillsDir = getClaudeSkillsDir();
    const codexSkillsDir = getCodexSkillsDir();
    const isCodex = isCodexInstalled();
    await mkdir(skillsDir, { recursive: true });
    if (isCodex)
        await mkdir(codexSkillsDir, { recursive: true });
    const rep = { installed: [], skipped: [], conflicts: [], uninstalled: [] };
    for (const name of SKILL_NAMES) {
        const src = join(pkg, 'skills', name);
        const dst = join(skillsDir, name);
        await linkSkill(name, src, dst, opts, rep, 'Claude Code');
        if (isCodex) {
            const codexDst = join(codexSkillsDir, name);
            await linkSkill(name, src, codexDst, opts, rep, 'Codex');
        }
    }
    // Wiki symlink: ~/.ae-tracking/wiki → <packageRoot>/wiki
    const wikiSrc = join(pkg, 'wiki');
    const wikiDst = join(getTeTrackingDir(), 'wiki');
    if (!opts.uninstall) {
        await mkdir(getTeTrackingDir(), { recursive: true });
        const wt = await linkTarget(wikiDst);
        if (wt === wikiSrc) {
            if (!opts.quiet)
                console.log(t('init.skipped_wiki'));
        }
        else if (wt === null) {
            await symlink(wikiSrc, wikiDst, 'dir');
            if (!opts.quiet)
                console.log(t('init.installed_wiki'));
        }
        else if (opts.force && wt !== 'NOT_SYMLINK') {
            await unlink(wikiDst);
            await symlink(wikiSrc, wikiDst, 'dir');
            if (!opts.quiet)
                console.log(t('init.installed_wiki_forced'));
        }
        else {
            if (!opts.quiet)
                console.warn(t('init.conflict_wiki'));
        }
    }
    else {
        const wt = await linkTarget(wikiDst);
        if (wt === wikiSrc) {
            await unlink(wikiDst);
            if (!opts.quiet)
                console.log(t('init.uninstalled_wiki'));
        }
    }
    // Codex AGENTS.md symlink: <cwd>/AGENTS.md → <cwd>/CLAUDE.md
    if (isCodex && !opts.uninstall) {
        const cwd = process.cwd();
        const claudeMdPath = join(cwd, CLAUDE_MD);
        const agentsMdPath = join(cwd, AGENTS_MD);
        const at = await linkTarget(agentsMdPath);
        if (at === claudeMdPath) {
            if (!opts.quiet)
                console.log(t('init.skipped_agents_md'));
        }
        else if (at === null) {
            await symlink(claudeMdPath, agentsMdPath, 'file');
            if (!opts.quiet)
                console.log(t('init.installed_agents_md'));
        }
        else if (opts.force && at !== 'NOT_SYMLINK') {
            await unlink(agentsMdPath);
            await symlink(claudeMdPath, agentsMdPath, 'file');
            if (!opts.quiet)
                console.log(t('init.installed_agents_md_forced'));
        }
        else {
            if (!opts.quiet)
                console.warn(t('init.conflict_agents_md'));
        }
    }
    else if (opts.uninstall && isCodex) {
        const cwd = process.cwd();
        const agentsMdPath = join(cwd, AGENTS_MD);
        const at = await linkTarget(agentsMdPath);
        if (at === join(cwd, CLAUDE_MD)) {
            await unlink(agentsMdPath);
            if (!opts.quiet)
                console.log(t('init.uninstalled_agents_md'));
        }
    }
    if (!opts.quiet) {
        for (const n of rep.installed)
            console.log(t('init.installed_skill', { name: n }));
        for (const n of rep.skipped)
            console.log(t('init.skipped_skill', { name: n }));
        for (const n of rep.conflicts)
            console.warn(t('init.conflict_skill', { name: n }));
        for (const n of rep.uninstalled)
            console.log(t('init.uninstalled_skill', { name: n }));
    }
    return rep;
}
export function registerInit(cmd) {
    cmd.description('install/uninstall Claude Code skills into ~/.claude/skills/')
        .option('--force', 'overwrite conflicting third-party symlinks')
        .option('--uninstall', 'remove symlinks that point to this package')
        .action(async (opts) => {
        await runInit({ force: opts.force, uninstall: opts.uninstall });
    });
}
