import process__default, { cwd } from 'node:process';
import { c as consola, P as ProjectAnalyzer, g as getTemplatesClient } from '../shared/ccjk.CoCHVXl3.mjs';
import { i18n } from './index2.mjs';
import { existsSync, readFileSync, writeFileSync, readdirSync } from 'node:fs';
import { CLAUDE_AGENTS_DIR } from './constants.mjs';
import { j as join, d as dirname } from '../shared/ccjk.bQ7Dh1g4.mjs';
import { w as writeAgentFile } from '../shared/ccjk.CfKKcvWy.mjs';
import { fileURLToPath } from 'node:url';
import { a as extractDisplayName, e as extractString } from '../shared/ccjk.C2jHOZVP.mjs';
import './index10.mjs';
import 'tinyglobby';
import '../shared/ccjk.BBtCGd_g.mjs';
import 'node:os';

const AGENTS_DIR = CLAUDE_AGENTS_DIR;
async function registerAgent(agent) {
  const agentId = "id" in agent ? agent.id : generateAgentId(agent);
  join(AGENTS_DIR, `${agentId}.json`);
  if (!existsSync(AGENTS_DIR)) ;
  const registryPath = join(AGENTS_DIR, "registry.json");
  let registry = {};
  if (existsSync(registryPath)) {
    try {
      registry = JSON.parse(readFileSync(registryPath, "utf-8"));
    } catch {
    }
  }
  registry[agentId] = {
    registeredAt: (/* @__PURE__ */ new Date()).toISOString(),
    version: "version" in agent ? agent.version : "1.0.0"
  };
  writeFileSync(registryPath, JSON.stringify(registry, null, 2));
}
function generateAgentId(agent) {
  const name = agent.name || agent.role || "agent";
  return `${name.toLowerCase().replace(/\s+/g, "-")}-${Date.now()}`;
}

function validateAgentDefinition(agent) {
  const errors = [];
  const warnings = [];
  if (!agent.id || agent.id.trim().length === 0) {
    errors.push({
      field: "id",
      message: "Agent ID is required",
      code: "MISSING_ID"
    });
  }
  if (!agent.persona || agent.persona.trim().length === 0) {
    errors.push({
      field: "persona",
      message: "Agent persona is required",
      code: "MISSING_PERSONA"
    });
  }
  if (!agent.instructions || agent.instructions.trim().length === 0) {
    errors.push({
      field: "instructions",
      message: "Agent instructions are required",
      code: "MISSING_INSTRUCTIONS"
    });
  }
  if (!agent.capabilities || agent.capabilities.length === 0) {
    warnings.push({
      field: "capabilities",
      message: "Agent has no capabilities defined",
      code: "NO_CAPABILITIES"
    });
  }
  if (!agent.skills || agent.skills.length === 0) {
    warnings.push({
      field: "skills",
      message: "Agent has no skills defined",
      code: "NO_SKILLS"
    });
  }
  return {
    valid: errors.length === 0,
    errors,
    warnings
  };
}

const _dirname = dirname(fileURLToPath(import.meta.url));
const AGENT_TEMPLATES_DIR = join(_dirname, "..", "templates", "agents");
const AGENT_TEMPLATES_DIR_DEV = join(_dirname, "..", "..", "templates", "agents");
function getAgentTemplatesDir() {
  if (existsSync(AGENT_TEMPLATES_DIR)) {
    return AGENT_TEMPLATES_DIR;
  }
  if (existsSync(AGENT_TEMPLATES_DIR_DEV)) {
    return AGENT_TEMPLATES_DIR_DEV;
  }
  return join(process.cwd(), "templates", "agents");
}
async function loadAgentTemplates() {
  const templatesDir = getAgentTemplatesDir();
  if (!existsSync(templatesDir)) {
    return [];
  }
  const templates = [];
  const files = readdirSync(templatesDir);
  for (const file of files) {
    if (!file.endsWith(".json"))
      continue;
    try {
      const filePath = join(templatesDir, file);
      const content = readFileSync(filePath, "utf-8");
      const template = JSON.parse(content);
      const recommendation = {
        name: template.name?.en || template.id || file.replace(".json", ""),
        description: template.description?.en || "No description available",
        skills: template.skills || [],
        mcpServers: template.mcpServers || [],
        persona: template.persona,
        capabilities: template.capabilities || [],
        tags: template.metadata?.tags || [],
        confidence: 0.8,
        reason: `Matches project type and includes relevant skills: ${(template.skills || []).join(", ")}`
      };
      templates.push(recommendation);
    } catch (error) {
      console.warn(`Failed to load agent template ${file}:`, error);
    }
  }
  return templates;
}

async function ccjkAgents(options = {}) {
  try {
    if (options.lang) {
      i18n.changeLanguage(options.lang);
    }
    const isZh = i18n.language === "zh-CN";
    if (options.list) {
      await listAgents();
      return;
    }
    if (options.delete) {
      consola.warn(isZh ? "\u5220\u9664\u529F\u80FD\u6682\u672A\u5B9E\u73B0" : "Delete functionality not yet implemented");
      return;
    }
    if (!options.json) {
      consola.info(isZh ? "\u{1F50D} \u5206\u6790\u9879\u76EE\u4E2D..." : "\u{1F50D} Analyzing project...");
    }
    const analyzer = new ProjectAnalyzer();
    const analysis = await analyzer.analyze(cwd());
    if (options.json) {
      console.log(JSON.stringify({
        analysis,
        recommendations: []
      }, null, 2));
      return;
    }
    const projectType = analysis.projectType;
    const frameworks = analysis.frameworks.map((f) => f.name);
    const languages = analysis.languages.map((l) => l.language);
    consola.success(`${isZh ? "\u68C0\u6D4B\u5230" : "Detected"}: ${projectType}`);
    if (frameworks.length > 0) {
      consola.info(`${isZh ? "\u6846\u67B6" : "Frameworks"}: ${frameworks.join(", ")}`);
    }
    if (languages.length > 0) {
      consola.info(`${isZh ? "\u8BED\u8A00" : "Languages"}: ${languages.join(", ")}`);
    }
    consola.log("");
    consola.info(isZh ? "\u{1F4CB} \u83B7\u53D6\u63A8\u8350\u4E2D..." : "\u{1F4CB} Getting recommendations...");
    const allTemplates = await loadAgentTemplates();
    let recommendations = allTemplates.filter(
      (t) => t.skills.some(
        (skill) => frameworks.includes(skill) || languages.includes(skill) || projectType.includes(skill)
      ) || t.capabilities.some(
        (cap) => frameworks.includes(cap) || languages.includes(cap) || projectType.includes(cap)
      ) || (t.tags || []).some(
        (tag) => frameworks.some((fw) => fw.toLowerCase().includes(tag) || tag.includes(fw.toLowerCase())) || languages.some((lang) => lang.toLowerCase().includes(tag) || tag.includes(lang.toLowerCase())) || projectType.toLowerCase().includes(tag)
      )
    );
    if (recommendations.length === 0) {
      recommendations = allTemplates;
    }
    try {
      const templatesClient = getTemplatesClient({ language: isZh ? "zh-CN" : "en" });
      const cloudAgents = await Promise.race([
        templatesClient.getSpecialistAgents(),
        new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
      ]);
      const relevantAgents = cloudAgents.filter((agent) => {
        const tags = agent.tags || [];
        const category = agent.category || "";
        const compatibility = agent.compatibility || {};
        return frameworks.some((fw) => tags.includes(fw.toLowerCase()) || category.includes(fw.toLowerCase())) || languages.some((lang) => tags.includes(lang.toLowerCase()) || (compatibility.languages || []).includes(lang.toLowerCase())) || tags.includes(projectType.toLowerCase());
      });
      const localAgentNames = new Set(recommendations.map((a) => (typeof a.name === "string" ? a.name : "").toLowerCase()));
      const cloudToAdd = relevantAgents.length > 0 ? relevantAgents : cloudAgents.slice(0, 10);
      for (const agent of cloudToAdd) {
        const agentName = (agent.name_zh_cn && isZh ? agent.name_zh_cn : agent.name_en).toLowerCase();
        if (localAgentNames.has(agentName)) {
          continue;
        }
        recommendations.push({
          name: agent.name_zh_cn && isZh ? agent.name_zh_cn : agent.name_en,
          description: agent.description_zh_cn && isZh ? agent.description_zh_cn : agent.description_en || "",
          skills: agent.tags || [],
          mcpServers: [],
          persona: agent.name_en,
          capabilities: [],
          confidence: agent.rating_average / 5 || 0.8,
          reason: `${isZh ? "\u63A8\u8350\u7406\u7531" : "Recommended"}: ${agent.category}`
        });
      }
      if (cloudToAdd.length > 0) {
        consola.success(isZh ? `\u4ECE\u4E91\u7AEF\u83B7\u53D6 ${cloudToAdd.length} \u4E2A\u4E13\u4E1A\u4EE3\u7406` : `Fetched ${cloudToAdd.length} specialist agents from cloud`);
      }
    } catch {
    }
    consola.log("");
    consola.info(`${isZh ? "\u627E\u5230" : "Found"} ${recommendations.length} ${isZh ? "\u4E2A\u63A8\u8350\u4EE3\u7406" : "recommended agent(s)"}:`);
    consola.log("");
    recommendations.forEach((agent, index) => {
      const displayName = extractDisplayName(agent.name, isZh);
      const displayDesc = extractDisplayName(agent.description, isZh, "No description available");
      consola.log(`  ${index + 1}. ${displayName}`);
      consola.log(`     ${displayDesc}`);
      if (agent.skills && agent.skills.length > 0) {
        consola.log(`     ${isZh ? "\u6280\u80FD" : "Skills"}: ${agent.skills.join(", ")}`);
      }
      if (agent.mcpServers && agent.mcpServers.length > 0) {
        consola.log(`     MCP: ${agent.mcpServers.join(", ")}`);
      }
      consola.log("");
    });
    if (!options.mode) {
      if (options.all) {
        options.mode = "auto";
      } else if (options.template || options.skills || options.persona) {
        options.mode = "custom";
      } else {
        options.mode = "auto";
      }
    }
    const createdAgents = [];
    switch (options.mode) {
      case "auto":
        if (!options.dryRun) {
          consola.log("");
          consola.info(isZh ? "\u{1F916} \u521B\u5EFA\u4EE3\u7406\u4E2D..." : "\u{1F916} Creating agents...");
        }
        for (const recommendation of recommendations) {
          const agentName = await createAgent(recommendation, options);
          if (agentName) {
            createdAgents.push(agentName);
            if (!options.dryRun) {
              consola.success(`${isZh ? "\u5DF2\u521B\u5EFA" : "Created"}: ${agentName}`);
            }
          }
        }
        break;
      case "template":
        let selectedTemplate = options.template;
        if (!selectedTemplate && recommendations.length > 0) {
          selectedTemplate = recommendations[0].name;
        }
        const template = recommendations.find((r) => r.name === selectedTemplate);
        if (template) {
          const agentName = await createAgent(template, options);
          if (agentName) {
            createdAgents.push(agentName);
          }
        }
        break;
      case "custom":
        const customAgent = await createCustomAgent(options);
        if (customAgent) {
          createdAgents.push(customAgent);
        }
        break;
    }
    if (!options.dryRun) {
      consola.log("");
      if (createdAgents.length > 0) {
        consola.success(`${isZh ? "\u2705 \u6210\u529F\u521B\u5EFA" : "\u2705 Successfully created"} ${createdAgents.length} ${isZh ? "\u4E2A\u4EE3\u7406" : "agent(s)"}`);
        consola.log("");
        consola.info(isZh ? "\u7528\u6CD5:" : "Usage:");
        createdAgents.forEach((agent) => {
          consola.log(`  /agent ${agent}`);
        });
        consola.log(`  ${isZh ? "\u67E5\u770B\u6240\u6709\u4EE3\u7406" : "List all agents"}: /agent list`);
      } else {
        consola.warn(isZh ? "\u672A\u521B\u5EFA\u4EFB\u4F55\u4EE3\u7406" : "No agents created");
      }
    } else {
      consola.log("");
      consola.info(isZh ? "\u{1F50D} Dry run \u5B8C\u6210" : "\u{1F50D} Dry run complete");
    }
  } catch (error) {
    const isZh = i18n.language === "zh-CN";
    consola.error(isZh ? "\u4EE3\u7406\u521B\u5EFA\u5931\u8D25" : "Agent creation failed", error);
    process__default.exit(1);
  }
}
async function listAgents() {
  const isZh = i18n.language === "zh-CN";
  const templates = await loadAgentTemplates();
  consola.log("");
  consola.info(`${isZh ? "\u53EF\u7528\u7684\u4EE3\u7406\u6A21\u677F" : "Available Agent Templates"} (${templates.length}):`);
  consola.log("");
  templates.forEach((agent, index) => {
    consola.log(`  ${index + 1}. ${agent.name}`);
    consola.log(`     ${agent.description}`);
    if (agent.skills && agent.skills.length > 0) {
      consola.log(`     ${isZh ? "\u6280\u80FD" : "Skills"}: ${agent.skills.join(", ")}`);
    }
    consola.log("");
  });
}
async function createAgent(recommendation, options) {
  try {
    const isZh = i18n.language === "zh-CN";
    const agentName = extractString(recommendation.name, "unknown-agent");
    const agentDescription = extractString(recommendation.description, "No description available");
    const agentDef = {
      id: agentName.toLowerCase().replace(/\s+/g, "-"),
      name: {
        "en": agentName,
        "zh-CN": agentName
      },
      description: {
        "en": agentDescription,
        "zh-CN": agentDescription
      },
      persona: recommendation.persona || agentName,
      instructions: agentDescription,
      skills: (recommendation.skills || []).map((skill) => ({
        pluginId: "local-agent",
        skillId: skill
      })),
      mcpServers: (recommendation.mcpServers || []).map((server) => ({
        serverName: server
      })),
      capabilities: recommendation.capabilities || []
    };
    const validation = validateAgentDefinition(agentDef);
    if (!validation.valid) {
      consola.error(`${isZh ? "\u9A8C\u8BC1\u5931\u8D25" : "Validation failed"}: ${agentName}`, validation.errors);
      return null;
    }
    if (options.dryRun) {
      consola.info(`[DRY RUN] ${isZh ? "\u5C06\u521B\u5EFA\u4EE3\u7406" : "Would create agent"}: ${agentName}`);
      return agentName;
    }
    await writeAgentFile(agentDef, {
      projectDir: cwd(),
      global: false
    });
    await registerAgent(agentDef);
    return agentName;
  } catch (error) {
    const isZh = i18n.language === "zh-CN";
    const errorName = extractString(recommendation.name, "unknown");
    consola.error(`${isZh ? "\u521B\u5EFA\u5931\u8D25" : "Failed to create"}: ${errorName}`, error);
    return null;
  }
}
async function createCustomAgent(options) {
  try {
    const isZh = i18n.language === "zh-CN";
    let agentName = options.create || options.template;
    if (!agentName) {
      agentName = "my-custom-agent";
    }
    const description = options.persona || "A custom AI agent for specific tasks";
    const skills = options.skills || [];
    const mcpServers = options.mcpServers || [];
    const agentDef = {
      id: agentName.toLowerCase().replace(/\s+/g, "-"),
      name: {
        "en": agentName,
        "zh-CN": agentName
      },
      description: {
        "en": description,
        "zh-CN": description
      },
      persona: options.persona || agentName,
      instructions: description,
      skills: skills.map((skill) => ({
        pluginId: "local-agent",
        skillId: skill
      })),
      mcpServers: mcpServers.map((server) => ({
        serverName: server
      })),
      capabilities: options.capabilities || []
    };
    const validation = validateAgentDefinition(agentDef);
    if (!validation.valid) {
      consola.error(isZh ? "\u9A8C\u8BC1\u9519\u8BEF" : "Validation errors", validation.errors);
      return null;
    }
    if (options.dryRun) {
      consola.info(`[DRY RUN] ${isZh ? "\u5C06\u521B\u5EFA\u81EA\u5B9A\u4E49\u4EE3\u7406" : "Would create custom agent"}: ${agentName}`);
      return agentName;
    }
    await writeAgentFile(agentDef, {
      projectDir: cwd(),
      global: false
    });
    await registerAgent(agentDef);
    return agentName;
  } catch (error) {
    const isZh = i18n.language === "zh-CN";
    consola.error(isZh ? "\u81EA\u5B9A\u4E49\u4EE3\u7406\u521B\u5EFA\u5931\u8D25" : "Custom agent creation failed", error);
    return null;
  }
}

export { ccjkAgents };
