/**
 * acr auth-recipe — 第三方服務認證 Recipe 管理
 *
 * acr auth-recipe list                 列出所有平台預建的 auth recipe（服務清單）
 * acr auth-recipe info <service>       顯示某服務的 recipe 詳情
 * acr auth-recipe scaffold <service>   輸出 credentials.yaml 範本 + workflow 使用範例
 */

import chalk from 'chalk';
import { loadConfig, getCypherExecutorUrl } from '../lib/config.js';

interface SecretRequirement {
  key: string;
  label: string;
  type?: 'string' | 'json_blob';
  help?: string;
  help_url?: string;
  optional?: boolean;
}

interface AuthInjectSpec {
  header?: Record<string, string>;
  query?: Record<string, string>;
  body?: Record<string, string>;
}

interface AuthRecipe {
  kind: 'auth_recipe';
  service: string;
  version: number;
  primitive: string;
  base_url: string;
  display_name?: string;
  description?: string;
  service_account_kind?: string;
  token_exchange?: { endpoint: string; scopes: string[] };
  required_secrets: SecretRequirement[];
  inject: AuthInjectSpec;
}

async function fetchAuthRecipes(baseUrl: string): Promise<AuthRecipe[]> {
  const res = await fetch(`${baseUrl}/auth-recipes`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const data = await res.json() as { recipes: AuthRecipe[] };
  return data.recipes ?? [];
}

async function fetchAuthRecipe(baseUrl: string, service: string): Promise<AuthRecipe | null> {
  const res = await fetch(`${baseUrl}/auth-recipes/${service}`);
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const data = await res.json() as { recipe: AuthRecipe };
  return data.recipe ?? null;
}

/** 輸出 credentials.yaml 範本 */
function buildCredentialsYaml(recipe: AuthRecipe): string {
  const lines: string[] = [
    `# credentials.yaml — ${recipe.display_name ?? recipe.service}`,
    `# 填入後執行：acr creds push`,
    ``,
  ];
  for (const s of recipe.required_secrets) {
    if (s.help) lines.push(`# ${s.label}`);
    if (s.help) lines.push(`# ${s.help}`);
    if (s.help_url) lines.push(`# 說明文件：${s.help_url}`);
    if (s.type === 'json_blob') {
      lines.push(`${s.key}: |`);
      lines.push(`  {`);
      lines.push(`    "type": "service_account",`);
      lines.push(`    ...`);
      lines.push(`  }`);
    } else {
      lines.push(`${s.key}: ""`);
    }
    lines.push(``);
  }
  return lines.join('\n');
}

/** 輸出 workflow.yaml config 範例 */
function buildWorkflowExample(recipe: AuthRecipe): string {
  const lines: string[] = [
    `# workflow.yaml — ${recipe.display_name ?? recipe.service} 使用範例`,
    ``,
    `name: my_workflow`,
    `triplets:`,
    `  - "input >> PIPE >> ${recipe.service}_call"`,
    `  - "${recipe.service}_call >> PIPE >> output"`,
    ``,
    `config:`,
    `  ${recipe.service}_call:`,
    `    component: ${recipe.service}`,
    `    method: POST`,
    `    _path: /your-endpoint-path`,
    `    # 其他參數依 API 文件填入`,
  ];
  return lines.join('\n');
}

export async function cmdAuthRecipeList(): Promise<void> {
  const config = loadConfig();
  const baseUrl = getCypherExecutorUrl(config);

  try {
    const recipes = await fetchAuthRecipes(baseUrl);

    if (recipes.length === 0) {
      console.log(chalk.yellow('  尚無 auth recipe。'));
      return;
    }

    // 依 primitive 分組
    const staticKey = recipes.filter(r => r.primitive === 'static_key');
    const serviceAccount = recipes.filter(r => r.primitive === 'service_account');
    const others = recipes.filter(r => r.primitive !== 'static_key' && r.primitive !== 'service_account');

    console.log(chalk.bold(`\n  第三方服務整合（${recipes.length} 個）\n`));

    if (staticKey.length) {
      console.log(chalk.gray('  API Key / Token 類：'));
      for (const r of staticKey) {
        const name = (r.display_name ?? r.service).padEnd(30);
        const secrets = r.required_secrets.map(s => s.key).join(', ');
        console.log(`    ${chalk.cyan(r.service.padEnd(22))} ${name} ${chalk.gray(`需要: ${secrets}`)}`);
      }
      console.log();
    }

    if (serviceAccount.length) {
      console.log(chalk.gray('  Service Account / JWT 類：'));
      for (const r of serviceAccount) {
        const name = (r.display_name ?? r.service).padEnd(30);
        const secrets = r.required_secrets.map(s => s.key).join(', ');
        console.log(`    ${chalk.cyan(r.service.padEnd(22))} ${name} ${chalk.gray(`需要: ${secrets}`)}`);
      }
      console.log();
    }

    if (others.length) {
      console.log(chalk.gray('  其他：'));
      for (const r of others) {
        console.log(`    ${chalk.cyan(r.service.padEnd(22))} ${r.display_name ?? r.service}`);
      }
      console.log();
    }

    console.log(chalk.gray(`  使用 acr auth-recipe scaffold <service> 查看設定範本\n`));
  } catch (e) {
    console.error(chalk.red(`  無法取得 auth recipe 清單：${e instanceof Error ? e.message : e}`));
    process.exit(1);
  }
}

export async function cmdAuthRecipeInfo(service: string): Promise<void> {
  const config = loadConfig();
  const baseUrl = getCypherExecutorUrl(config);

  try {
    const recipe = await fetchAuthRecipe(baseUrl, service);
    if (!recipe) {
      console.error(chalk.red(`  找不到 auth recipe：${service}`));
      console.log(chalk.gray(`  執行 acr auth-recipe list 查看所有可用服務`));
      process.exit(1);
    }

    console.log(chalk.bold(`\n  ${recipe.display_name ?? recipe.service}\n`));
    if (recipe.description) console.log(`  ${recipe.description}\n`);
    console.log(`  service:    ${recipe.service}`);
    console.log(`  primitive:  ${recipe.primitive}`);
    console.log(`  base_url:   ${recipe.base_url}`);
    if (recipe.token_exchange) {
      console.log(`  scopes:     ${recipe.token_exchange.scopes.join(', ')}`);
    }
    console.log(`\n  ${chalk.bold('需要的 credentials：')}`);
    for (const s of recipe.required_secrets) {
      console.log(`    ${chalk.cyan(s.key)}${s.optional ? chalk.gray(' (optional)') : ''}`);
      console.log(`      ${s.label}`);
      if (s.help) console.log(chalk.gray(`      ${s.help}`));
      if (s.help_url) console.log(chalk.gray(`      → ${s.help_url}`));
    }
    console.log();
  } catch (e) {
    console.error(chalk.red(`  錯誤：${e instanceof Error ? e.message : e}`));
    process.exit(1);
  }
}

export async function cmdAuthRecipeScaffold(service: string): Promise<void> {
  const config = loadConfig();
  const baseUrl = getCypherExecutorUrl(config);

  try {
    const recipe = await fetchAuthRecipe(baseUrl, service);
    if (!recipe) {
      console.error(chalk.red(`  找不到 auth recipe：${service}`));
      console.log(chalk.gray(`  執行 acr auth-recipe list 查看所有可用服務`));
      process.exit(1);
    }

    console.log(chalk.bold(`\n  ── credentials.yaml 範本 ────────────────────────────────\n`));
    console.log(buildCredentialsYaml(recipe));

    console.log(chalk.bold(`\n  ── workflow.yaml 範例 ───────────────────────────────────\n`));
    console.log(buildWorkflowExample(recipe));
    console.log();

    if (recipe.primitive === 'service_account') {
      console.log(chalk.yellow(
        `  注意（Service Account）：\n` +
        `  將整份 Service Account JSON 貼入 credentials.yaml 的 ${recipe.required_secrets[0].key} 欄位。\n` +
        `  格式：多行 YAML literal block（| 後換行縮排）。\n`
      ));
    }
  } catch (e) {
    console.error(chalk.red(`  錯誤：${e instanceof Error ? e.message : e}`));
    process.exit(1);
  }
}
