import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { createInterface } from 'node:readline/promises';
import { getTokenPath, getTeTrackingDir } from './home.js';
import { getToken, saveToken, clearToken } from '../auth.js';
import { t } from '../i18n/translate.js';
const DEFAULT_HOST = 'https://web-ta-demo.thinkingdata.cn';
async function loadCache() {
    try {
        return JSON.parse(await readFile(getTokenPath(), 'utf8'));
    }
    catch {
        return {};
    }
}
async function saveCache(cache) {
    await mkdir(getTeTrackingDir(), { recursive: true });
    await writeFile(getTokenPath(), JSON.stringify(cache, null, 2), 'utf8');
}
/**
 * 获取并缓存 token（可被其他命令调用）
 * macOS: 从 Chrome/Safari localStorage 自动获取
 * Windows/Linux: 引导用户手动获取并输入
 */
export async function refreshToken(host) {
    let token;
    let browser;
    if (process.platform === 'darwin') {
        // macOS: 从 Chrome/Safari 自动获取
        clearToken(host);
        const result = await getToken(host);
        token = result.token;
        browser = result.browser;
        if (browser && browser !== 'cache' && browser !== 'env') {
            console.log(t('auth.token_captured', { browser }));
        }
    }
    else {
        // Windows/Linux: guide user to manually get token
        console.log('\n' + t('auth.token_instructions_title'));
        console.log(t('auth.token_instructions_step1', { host }));
        console.log(t('auth.token_instructions_step2'));
        console.log(t('auth.token_instructions_step3'));
        console.log(t('auth.token_instructions_step4') + '\n');
        const rl = createInterface({ input: process.stdin, output: process.stdout });
        token = (await rl.question(t('auth.paste_prompt'))).trim();
        rl.close();
        if (!token) {
            throw new Error(t('auth.empty_token'));
        }
        saveToken(token, host);
    }
    const cache = await loadCache();
    cache[host] = { token, updatedAt: new Date().toISOString() };
    await saveCache(cache);
    console.log(t('auth.token_refreshed', { host }));
    return token;
}
async function cmdLogin(opts) {
    await refreshToken(opts.host);
    console.log(t('auth.token_cached', { host: opts.host }));
}
async function cmdStatus() {
    const cache = await loadCache();
    const entries = Object.entries(cache);
    if (entries.length === 0) {
        console.log(t('auth.no_cached_tokens'));
        return;
    }
    for (const [host, v] of entries) {
        console.log(`${host}  ${v.token.slice(0, 6)}...${v.token.slice(-4)}  updated ${v.updatedAt}`);
    }
}
async function cmdClear() {
    await saveCache({});
    console.log(t('auth.cache_cleared'));
}
export function registerAuth(cmd) {
    cmd.description('manage AE access tokens');
    cmd.command('login').option('--host <url>', 'AE host', DEFAULT_HOST).action(cmdLogin);
    cmd.command('status').action(cmdStatus);
    cmd.command('clear').action(cmdClear);
}
