/**
 * acr logs <workflow_name> — 顯示最近執行記錄
 */
import chalk from 'chalk';
import ora from 'ora';
import { loadConfig } from '../lib/config.js';
import { CfKvClient } from '../lib/cf-api.js';

export async function cmdLogs(workflowName: string): Promise<void> {
  const config = loadConfig();

  if (!config.cloudflare_account_id || !config.cf_api_token) {
    console.error(chalk.red('缺少 Cloudflare 設定，請執行 acr init'));
    process.exit(1);
  }

  const namespaceId = config.mode === 'standard'
    ? config.user_kv_namespace_id!
    : config.webhooks_kv_namespace_id!;

  if (!namespaceId) {
    console.error(chalk.red('缺少 KV Namespace ID，請執行 acr init'));
    process.exit(1);
  }

  const kv = new CfKvClient({
    accountId: config.cloudflare_account_id,
    namespaceId,
    apiToken: config.cf_api_token,
  });

  const spinner = ora(`讀取 "${workflowName}" 執行記錄`).start();

  try {
    const keys = await kv.list(`log:${workflowName}:`);
    spinner.stop();

    if (keys.length === 0) {
      console.log(chalk.yellow(`\n  "${workflowName}" 沒有執行記錄。\n`));
      return;
    }

    // 依時間排序（key 格式：log:{name}:{timestamp}）
    const sorted = keys.sort((a, b) => b.name.localeCompare(a.name)).slice(0, 20);

    console.log(chalk.bold(`\n  "${workflowName}" 最近 ${sorted.length} 次執行記錄\n`));

    for (const key of sorted) {
      try {
        const raw = await kv.get(key.name);
        if (!raw) continue;

        const log = JSON.parse(raw) as {
          success: boolean;
          duration_ms: number;
          executed_at: string;
          failed_node?: string;
          error?: string;
        };

        const icon = log.success ? chalk.green('✓') : chalk.red('✗');
        const date = new Date(log.executed_at).toLocaleString('zh-TW');
        const duration = chalk.gray(`${log.duration_ms}ms`);

        if (log.success) {
          console.log(`  ${icon} ${date}  ${duration}`);
        } else {
          console.log(`  ${icon} ${date}  ${duration}  ${chalk.red(`失敗節點：${log.failed_node ?? '未知'}`)}`);
          if (log.error) {
            console.log(chalk.red(`      ${log.error.slice(0, 100)}`));
          }
        }
      } catch {
        // 跳過無法解析的記錄
      }
    }
    console.log('');
  } catch (e) {
    spinner.fail(chalk.red(`KV 讀取失敗：${e instanceof Error ? e.message : e}`));
    process.exit(1);
  }
}
