import a from './index5.mjs';
import { getCloudBaseUrl } from './constants.mjs';
import { i18n } from './index2.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:os';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import 'node:fs';
import 'node:process';
import 'node:url';

class A2AClient {
  baseUrl;
  token = null;
  agentId = null;
  constructor(baseUrl) {
    const resolved = baseUrl || process.env.CCJK_SERVER_URL;
    if (!resolved) {
      if (process.env.NODE_ENV === "production") {
        throw new Error("CCJK_SERVER_URL is required in production");
      }
      this.baseUrl = "http://localhost:3005";
      return;
    }
    if (process.env.NODE_ENV === "production" && !resolved.startsWith("https://")) {
      throw new Error("CCJK_SERVER_URL must use https:// in production");
    }
    this.baseUrl = resolved;
  }
  /**
   * Register agent — POST /a2a/hello
   * Server expects: { agent: { name, version }, capabilities }
   */
  async hello(name, version, capabilities = []) {
    const response = await this.request("/a2a/hello", {
      method: "POST",
      body: { agent: { name, version }, capabilities }
    });
    this.token = response.token;
    this.agentId = response.agentId;
    return response;
  }
  /**
   * Publish a gene — POST /a2a/publish
   * Server expects flat fields: problemSignature, solutionStrategy, solutionCode, solutionSteps, tags, version
   */
  async publish(gene) {
    this.ensureAuthenticated();
    return this.request("/a2a/publish", {
      method: "POST",
      body: {
        problemSignature: gene.problemSignature,
        solutionStrategy: gene.solutionStrategy,
        solutionCode: gene.solutionCode || "",
        solutionSteps: gene.solutionSteps,
        tags: gene.tags || [],
        version: gene.version || "1.0.0"
      },
      auth: true
    });
  }
  /**
   * Fetch genes — GET /a2a/fetch?minGDI=&limit=&signature=
   * Server returns: { success, genes: [...] }
   */
  async fetch(options = {}) {
    this.ensureAuthenticated();
    const params = new URLSearchParams();
    if (options.minGDI !== void 0)
      params.set("minGDI", String(options.minGDI));
    if (options.limit !== void 0)
      params.set("limit", String(options.limit));
    if (options.signature)
      params.set("signature", options.signature);
    if (options.geneId)
      params.set("geneId", options.geneId);
    const qs = params.toString();
    const response = await this.request(`/a2a/fetch${qs ? `?${qs}` : ""}`, {
      method: "GET",
      auth: true
    });
    return response.genes;
  }
  /**
   * Report usage result — POST /a2a/report
   * Server expects: { geneId, outcome, context? }
   */
  async report(geneId, outcome, context) {
    this.ensureAuthenticated();
    return this.request("/a2a/report", {
      method: "POST",
      body: { geneId, outcome, ...context ? { context } : {} },
      auth: true
    });
  }
  /**
   * Record decision — POST /a2a/decision
   * Server expects: { geneId, action: 'approve' | 'reject' }
   */
  async decision(geneId, action) {
    this.ensureAuthenticated();
    return this.request("/a2a/decision", {
      method: "POST",
      body: { geneId, action },
      auth: true
    });
  }
  /**
   * Revoke a gene — POST /a2a/revoke
   * Server expects: { geneId, reason? }
   */
  async revoke(geneId, reason) {
    this.ensureAuthenticated();
    await this.request("/a2a/revoke", {
      method: "POST",
      body: { geneId, ...reason ? { reason } : {} },
      auth: true
    });
  }
  /**
   * Get stats — GET /a2a/stats
   */
  async stats() {
    this.ensureAuthenticated();
    const resp = await this.request("/a2a/stats", {
      method: "GET",
      auth: true
    });
    return resp.stats;
  }
  getAgentId() {
    return this.agentId;
  }
  isAuthenticated() {
    return this.token !== null;
  }
  async request(path, options) {
    const url = `${this.baseUrl}${path}`;
    const headers = {
      "Content-Type": "application/json"
    };
    if (options.auth && this.token) {
      headers.Authorization = `Bearer ${this.token}`;
    }
    const response = await globalThis.fetch(url, {
      method: options.method,
      headers,
      body: options.body ? JSON.stringify(options.body) : void 0
    });
    if (!response.ok) {
      const error = await response.json().catch(() => ({ error: response.statusText }));
      throw new Error(error.error || error.message || `Request failed: ${response.statusText}`);
    }
    return response.json();
  }
  ensureAuthenticated() {
    if (!this.token) {
      throw new Error("Not authenticated. Call hello() first.");
    }
  }
}

async function handleEvolutionCommand(action, args, options) {
  try {
    const client = new A2AClient(getCloudBaseUrl("MAIN"));
    await client.hello("ccjk", "1.0.0", ["fetch", "report", "publish"]);
    switch (action) {
      case "top":
        await showTopCapabilities(client, options);
        break;
      case "search":
        await searchSolutions(client, args[0], options);
        break;
      case "show":
        await showGeneDetails(client, args[0]);
        break;
      case "stats":
        await showStats(client);
        break;
      default:
        await showTopCapabilities(client, { limit: "30", minGdi: "70" });
    }
  } catch (error) {
    const failedMsg = i18n.t("evolution:failed", "Failed");
    console.error(a.red(`\u274C ${failedMsg}:`), error.message);
    process.exit(1);
  }
}
async function showTopCapabilities(client, options) {
  const fetchingMsg = i18n.t("evolution:fetching", "Fetching top capabilities...");
  console.log(a.blue(`\u{1F4CA} ${fetchingMsg}`));
  const genes = await client.fetch({
    minGDI: Number.parseInt(options.minGdi || "70"),
    limit: Number.parseInt(options.limit || "30")
  });
  const foundMsg = i18n.t("evolution:found", "Found {{count}} capabilities", { count: genes.length });
  console.log(a.green(`
\u2705 ${foundMsg}
`));
  if (genes.length === 0) {
    const noResultsMsg = i18n.t("evolution:noResults", "No capabilities found");
    console.log(a.yellow(noResultsMsg));
    return;
  }
  genes.forEach((gene, index) => {
    console.log(a.bold(`${index + 1}. ${gene.geneId.substring(0, 8)}`));
    const problemLabel = a.cyan(i18n.t("evolution:problem", "Problem"));
    console.log(`   ${problemLabel}: ${gene.problemSignature}`);
    const solutionLabel = a.yellow(i18n.t("evolution:solution", "Solution"));
    console.log(`   ${solutionLabel}: ${gene.solutionStrategy}`);
    console.log(`   ${a.green("GDI")}: ${gene.gdi.toFixed(1)}`);
    const usedLabel = a.gray(i18n.t("evolution:used", "Used"));
    const timesLabel = i18n.t("evolution:times", "times");
    console.log(`   ${usedLabel}: ${gene.usageCount} ${timesLabel}`);
    const successLabel = a.gray(i18n.t("evolution:success", "Success"));
    const successRate = (gene.successRate * 100).toFixed(1);
    console.log(`   ${successLabel}: ${successRate}%`);
    console.log();
  });
}
async function searchSolutions(client, query, options) {
  const searchingMsg = i18n.t("evolution:searching", "Searching for: {{query}}", { query });
  console.log(a.blue(`\u{1F50D} ${searchingMsg}`));
  const genes = await client.fetch({
    signature: query,
    minGDI: Number.parseInt(options.minGdi || "60"),
    limit: Number.parseInt(options.limit || "10")
  });
  if (genes.length === 0) {
    const noSolutionsMsg = i18n.t("evolution:noSolutions", "No solutions found");
    console.log(a.yellow(`
${noSolutionsMsg}`));
    return;
  }
  const foundMsg = i18n.t("evolution:foundSolutions", "Found {{count}} solutions", { count: genes.length });
  console.log(a.green(`
\u2705 ${foundMsg}
`));
  genes.forEach((gene, index) => {
    console.log(a.bold(`${index + 1}. ${gene.problemSignature}`));
    console.log(`   ${gene.solutionStrategy}`);
    const usedLabel = i18n.t("evolution:used", "Used");
    console.log(`   GDI: ${gene.gdi.toFixed(1)} | ${usedLabel}: ${gene.usageCount}x`);
    if (gene.tags.length > 0) {
      const tagsLabel = a.gray(i18n.t("evolution:tags", "Tags"));
      console.log(`   ${tagsLabel}: ${gene.tags.join(", ")}`);
    }
    console.log();
  });
}
async function showGeneDetails(client, geneId) {
  const genes = await client.fetch({ geneId, limit: 5 });
  const gene = genes.find((g) => g.geneId.startsWith(geneId));
  if (!gene) {
    const notFoundMsg = i18n.t("evolution:geneNotFound", "Gene not found");
    console.log(a.red(notFoundMsg));
    return;
  }
  displayGene(gene);
}
async function showStats(client) {
  const fetchingMsg = i18n.t("evolution:fetchingStats", "Fetching statistics...");
  console.log(a.blue(`\u{1F4CA} ${fetchingMsg}`));
  const stats = await client.stats();
  console.log(a.bold("\n\u{1F4C8} Evolution Layer Statistics\n"));
  const totalLabel = a.cyan(i18n.t("evolution:totalGenes", "Total Genes in Pool"));
  console.log(`${totalLabel}: ${stats.totalGenesInPool}`);
  const myLabel = a.cyan(i18n.t("evolution:myContributions", "My Contributions"));
  console.log(`${myLabel}: ${stats.myContributions}`);
  const reportsLabel = a.cyan(i18n.t("evolution:reportsSubmitted", "Reports Submitted"));
  console.log(`${reportsLabel}: ${stats.reportsSubmitted}`);
  const successLabel = a.cyan(i18n.t("evolution:successRate", "Success Rate"));
  console.log(`${successLabel}: ${(stats.successRate * 100).toFixed(1)}%`);
}
function displayGene(gene) {
  const detailsLabel = i18n.t("evolution:geneDetails", "Gene Details");
  console.log(a.bold(`
\u{1F4E6} ${detailsLabel}
`));
  console.log(`${a.cyan("ID")}: ${gene.geneId}`);
  console.log(`${a.cyan("Version")}: ${gene.version}`);
  console.log();
  const problemLabel = i18n.t("evolution:problem", "Problem");
  console.log(a.bold(`${problemLabel}:`));
  console.log(`  ${gene.problemSignature}`);
  console.log();
  const solutionLabel = i18n.t("evolution:solution", "Solution");
  console.log(a.bold(`${solutionLabel}:`));
  const strategyLabel = i18n.t("evolution:strategy", "Strategy");
  console.log(`  ${strategyLabel}: ${gene.solutionStrategy}`);
  if (gene.solutionCode) {
    const codeLabel = i18n.t("evolution:code", "Code");
    console.log(`  ${codeLabel}:`);
    const codeLines = gene.solutionCode.split("\n").map((line) => `    ${line}`).join("\n");
    console.log(a.gray(codeLines));
  }
  if (gene.solutionSteps.length > 0) {
    const stepsLabel = i18n.t("evolution:steps", "Steps");
    console.log(`  ${stepsLabel}:`);
    gene.solutionSteps.forEach((step, i) => {
      console.log(`    ${i + 1}. ${step}`);
    });
  }
  console.log();
  const qualityLabel = i18n.t("evolution:quality", "Quality");
  console.log(a.bold(`${qualityLabel}:`));
  console.log(`  GDI: ${gene.gdi.toFixed(1)}`);
  const successRateLabel = i18n.t("evolution:successRate", "Success Rate");
  console.log(`  ${successRateLabel}: ${(gene.successRate * 100).toFixed(1)}%`);
  const usageCountLabel = i18n.t("evolution:usageCount", "Usage Count");
  console.log(`  ${usageCountLabel}: ${gene.usageCount}`);
  const passRateLabel = i18n.t("evolution:passRate", "Pass Rate");
  console.log(`  ${passRateLabel}: ${(gene.passRate * 100).toFixed(1)}%`);
  if (gene.tags.length > 0) {
    console.log();
    const tagsLabel = i18n.t("evolution:tags", "Tags");
    console.log(`  ${tagsLabel}: ${gene.tags.join(", ")}`);
  }
  const createdLabel = i18n.t("evolution:createdAt", "Created At");
  console.log(`  ${createdLabel}: ${gene.createdAt}`);
}

export { handleEvolutionCommand };
