#!/usr/bin/env bun
/**
 * hwlab-code-agent CLI — HWLAB Code Agent 客户端
 * Skill(cli-spec)
 *
 * 通过 hwlab-code-agent 直接调 HWLAB v0.2 cloud-api 管理 agent turn：
 *   spawn  - 创建 session + 提交 prompt，立即返回 traceId
 *   poll   - 轮询等待 turn 完成
 *   result - 查询 turn 结果
 *   trace  - 查询 turn trace
 */

import path from "node:path";
import { spawn, poll, getResult, getTrace } from "./src/client.ts";

const argv = process.argv.slice(2);
const cmd = argv[0];

function parseArgs(from: number): Record<string, string | undefined> {
  const args: Record<string, string | undefined> = {};
  for (let i = from; i < argv.length; i++) {
    if (argv[i].startsWith("--")) {
      const key = argv[i].slice(2);
      const val = (i + 1 < argv.length && !argv[i + 1].startsWith("--")) ? argv[i + 1] : "true";
      args[key] = val;
      if (val !== "true") i++;
    }
  }
  return args;
}

async function main() {
  switch (cmd) {
    case "spawn": {
      const args = parseArgs(1);
      await spawn(args);
      break;
    }
    case "poll": {
      const traceId = argv[1];
      if (!traceId) {
        process.stderr.write(JSON.stringify({ ok: false, error: { code: "usage", message: "poll <traceId> [--timeout N]" } }) + "\n");
        process.exit(1);
      }
      await poll(traceId, parseArgs(2));
      break;
    }
    case "result": {
      const traceId = argv[1];
      if (!traceId) {
        process.stderr.write(JSON.stringify({ ok: false, error: { code: "usage", message: "result <traceId>" } }) + "\n");
        process.exit(1);
      }
      await getResult(traceId);
      break;
    }
    case "trace": {
      const traceId = argv[1];
      if (!traceId) {
        process.stderr.write(JSON.stringify({ ok: false, error: { code: "usage", message: "trace <traceId> [--full]" } }) + "\n");
        process.exit(1);
      }
      await getTrace(traceId, parseArgs(2));
      break;
    }
    default:
      process.stderr.write(JSON.stringify({
        ok: false,
        usage: {
          spawn: "HWLAB_CODE_AGENT_PROVIDER_PROFILE=PROFILE bun scripts/hwlab-code-agent-cli.ts spawn --message '...' [--profile PROFILE]",
          poll:   "bun scripts/hwlab-code-agent-cli.ts poll <traceId> [--timeout 600000]",
          result: "bun scripts/hwlab-code-agent-cli.ts result <traceId>",
          trace:  "bun scripts/hwlab-code-agent-cli.ts trace <traceId> [--full]"
        }
      }, null, 2) + "\n");
      process.exit(1);
  }
}

main().catch((e) => {
  process.stderr.write(JSON.stringify({ ok: false, error: { code: "unhandled", message: e.message } }) + "\n");
  process.exit(1);
});
