import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { getConfigDir } from '../config.js';
import { detectCliLocale } from '../i18n/locale.js';
const SUPPORTED = ['zh', 'en', 'ja', 'ko'];
const SUPPORTED_LABELS = {
    zh: '中文 (Chinese)',
    en: 'English',
    ja: '日本語 (Japanese)',
    ko: '한국어 (Korean)',
};
function langConfigPath() {
    return join(getConfigDir(), 'config.json');
}
function readLangConfig() {
    try {
        return JSON.parse(readFileSync(langConfigPath(), 'utf8'));
    }
    catch {
        return {};
    }
}
function writeLangConfig(cfg) {
    mkdirSync(getConfigDir(), { recursive: true });
    writeFileSync(langConfigPath(), JSON.stringify(cfg, null, 2));
}
export function getSavedLang() {
    const raw = readLangConfig().lang;
    if (raw && SUPPORTED.includes(raw))
        return raw;
    return undefined;
}
export function registerLang(cmd) {
    cmd.description('manage CLI display language');
    cmd.command('set')
        .description('set the CLI language')
        .argument('<locale>', 'language code: zh / en / ja / ko')
        .action((locale) => {
        const normalized = locale.trim().toLowerCase();
        if (!SUPPORTED.includes(normalized)) {
            console.error(`❌ Unsupported language: "${locale}"`);
            console.error('Supported languages:');
            for (const code of SUPPORTED) {
                console.error(`  ${code} — ${SUPPORTED_LABELS[code]}`);
            }
            process.exit(1);
        }
        const cfg = readLangConfig();
        cfg.lang = normalized;
        writeLangConfig(cfg);
        console.log(`Language set to: ${SUPPORTED_LABELS[normalized]} (${normalized})`);
        console.log('Run any ae-tracking command to see the change.');
    });
    cmd.command('status')
        .description('show current language settings')
        .action(() => {
        const saved = getSavedLang();
        const sys = process.env.LANG || process.env.LC_ALL || '';
        const current = detectCliLocale();
        console.log('CLI language settings:');
        console.log();
        if (process.env.AE_LANG) {
            console.log(`  AE_LANG env var: ${process.env.AE_LANG}  ← active`);
        }
        else if (saved) {
            console.log(`  Saved preference: ${saved} (${SUPPORTED_LABELS[saved]})  ← active`);
        }
        else {
            console.log(`  System locale: ${sys || '(not set)'}`);
            console.log(`  Detected: ${current} (${SUPPORTED_LABELS[current]})  ← active`);
        }
        console.log(`  Fallback: en`);
        console.log();
        console.log('Supported languages:');
        for (const code of SUPPORTED) {
            const marker = code === current ? ' ← current' : '';
            console.log(`  ${code} — ${SUPPORTED_LABELS[code]}${marker}`);
        }
        console.log();
        console.log('To change: ae-tracking lang set <code>');
    });
    cmd.command('reset')
        .description('reset to follow system locale')
        .action(() => {
        const cfg = readLangConfig();
        delete cfg.lang;
        writeLangConfig(cfg);
        console.log('Language reset. Will follow system locale on next command.');
    });
}
