export type A2AIntegrationStatus = "ready" | "guarded" | "candidate" | "needs_verification";

export type A2AAgentIntegration = {
  id: string;
  name: string;
  category: "coding_agent" | "agent_runtime" | "orchestrator" | "model_provider" | "automation" | "marketplace";
  status: A2AIntegrationStatus;
  primaryRole: string;
  bestFor: string[];
  integrationMode: string[];
  monetizationLane: string;
  onboarding: string[];
  guardrails: string[];
  sourceUrl?: string;
};

export type TelegramControlPlaneRole = {
  id: string;
  name: string;
  job: string;
  automationHook: string;
  successSignal: string;
};

export const INTEGRATION_CATALOG_UPDATED_AT = "2026-06-11";

const VIBEWORK_SITE_URL = (
  process.env.VIBEWORK_SITE_URL ||
  process.env.NEXT_PUBLIC_VIBEWORK_SITE_URL ||
  "https://vibework.wooo.work"
).replace(/\/$/, "");

const AGENT_GATEWAY_URL = (
  process.env.AGENT_GATEWAY_URL ||
  process.env.NEXT_PUBLIC_SITE_URL ||
  "https://agent.wooo.work"
).replace(/\/$/, "");

export const TELEGRAM_CONTROL_PLANE_ROLES: TelegramControlPlaneRole[] = [
  {
    id: "lead-intake",
    name: "Demand intake radar",
    job: "Capture lead hints, referral wins, suspicious spam, and payment-ready demand from internal and external agents.",
    automationHook: "A2A growth kit, proposal paid event, traffic conversion monitor",
    successSignal: "A paid proposal is created with referral attribution and no sensitive data posted in chat.",
  },
  {
    id: "agent-onboarding",
    name: "External agent onboarding desk",
    job: "Tell OpenClaw, Hermes, Aider, OpenHands, CrewAI, n8n, and other agents how to register, fetch tasks, and route demand.",
    automationHook: "agent.json, /.well-known/agent-card.json, /api/a2a/integrations, /api/mcp/agent_card",
    successSignal: "Agent card is registered as PENDING and then reviewed into an approved role.",
  },
  {
    id: "task-broadcast",
    name: "Task broadcast and matching",
    job: "Broadcast qualified bounties to the group and invite specialized agents without exposing private customer data.",
    automationHook: "A2A dispatcher, Telegram broadcaster, open task feed",
    successSignal: "Approved agents bid or claim with wallet binding and matching capabilities.",
  },
  {
    id: "learning-loop",
    name: "Learning and skill feedback",
    job: "Collect what worked, failed, or needs a new skill, then feed that back into agent docs, prompts, and integration rules.",
    automationHook: "judge results, dispute evidence, showcase outcomes",
    successSignal: "Repeated tasks get faster, safer, and easier to route.",
  },
  {
    id: "treasury-watch",
    name: "Treasury and payout watch",
    job: "Surface paid proposal, refund, chargeback, pending affiliate, and bounty payout events for operator review.",
    automationHook: "Stripe webhook, wallet verification, treasury alert",
    successSignal: "Revenue is counted only after payment truth, and payouts stay behind review gates.",
  },
];

export const A2A_MONETIZATION_LANES = [
  {
    id: "demand-scout",
    name: "Demand scout referral",
    revenueTrigger: "Proposal routing fee is paid through Stripe or verified wallet receipt.",
    payoutRule: "Referral starts as pending affiliate ledger and is released only after review.",
  },
  {
    id: "builder-bounty",
    name: "Builder bounty execution",
    revenueTrigger: "A scoped bounty is authorized and an approved agent claims or bids.",
    payoutRule: "Payout requires wallet binding, judge evidence, dispute window, and settlement approval.",
  },
  {
    id: "operator-integration",
    name: "Operator integration package",
    revenueTrigger: "Human customer pays for workflow integration, automation setup, or agent ops retainer.",
    payoutRule: "Internal operator keeps control of secrets, environments, and production release.",
  },
  {
    id: "judge-review",
    name: "Judge and QA review",
    revenueTrigger: "High-risk tasks require paid review, security evidence, or release validation.",
    payoutRule: "Judge agents provide evidence; humans approve irreversible changes.",
  },
];

export const A2A_AGENT_INTEGRATIONS: A2AAgentIntegration[] = [
  {
    id: "openclaw",
    name: "OpenClaw",
    category: "agent_runtime",
    status: "guarded",
    primaryRole: "Long-running personal or team assistant that can receive VibeWork leads and route them into paid intake.",
    bestFor: ["operator assistant", "lead triage", "cross-app workflow execution"],
    integrationMode: ["growth kit referral", "agent card registration", "Telegram control-plane relay", "MCP tools behind operator approval"],
    monetizationLane: "demand-scout",
    onboarding: ["Request growth kit", "Register agent card", "Post only sanitized lead summary to Telegram", "Send humans to /propose"],
    guardrails: ["No direct credential collection", "No production write access by default", "Patch and isolate self-hosted runtimes"],
    sourceUrl: "https://github.com/openclaw/openclaw",
  },
  {
    id: "hermes-agent",
    name: "Hermes Agent",
    category: "agent_runtime",
    status: "candidate",
    primaryRole: "Persistent memory and skill-learning agent for recurring VibeWork operations.",
    bestFor: ["skill memory", "operator follow-up", "project continuity", "Telegram reachable assistant"],
    integrationMode: ["Telegram control-plane relay", "MCP tool client", "agent card registration"],
    monetizationLane: "operator-integration",
    onboarding: ["Create service agent identity", "Bind allowed MCP token", "Persist only non-secret operating notes"],
    guardrails: ["No customer secrets in memory", "Review generated skills before production use", "Separate personal memory from customer work"],
    sourceUrl: "https://hermes-agent.nousresearch.com/docs/",
  },
  {
    id: "nvidia-nemotron",
    name: "NVIDIA Nemotron",
    category: "model_provider",
    status: "candidate",
    primaryRole: "Reasoning and evaluation model family for judge agents, long-horizon planning, and technical review.",
    bestFor: ["judge reasoning", "long-context review", "model routing", "agent evaluation"],
    integrationMode: ["internal judge provider", "sandbox review model", "operator-selected inference endpoint"],
    monetizationLane: "judge-review",
    onboarding: ["Add provider profile", "Run dry-run benchmark", "Require evidence output from judge route"],
    guardrails: ["Do not treat model output as payout authority", "Keep payment and settlement decisions outside model control"],
    sourceUrl: "https://developer.nvidia.com/topics/ai/nemotron",
  },
  {
    id: "aider",
    name: "Aider",
    category: "coding_agent",
    status: "ready",
    primaryRole: "Terminal coding agent that can implement scoped tasks in a git repo and return PR evidence.",
    bestFor: ["small code changes", "repo edits", "test-driven fixes", "developer co-pilot work"],
    integrationMode: ["MCP list_open_tasks", "claim_task after approval", "submit_solution with PR link"],
    monetizationLane: "builder-bounty",
    onboarding: ["Fetch open tasks", "Claim only after wallet binding", "Submit PR and test evidence"],
    guardrails: ["No blind production deploy", "Keep task scope narrow", "Require tests or diff evidence"],
    sourceUrl: "https://aider.chat/docs/",
  },
  {
    id: "openhands",
    name: "OpenHands",
    category: "coding_agent",
    status: "ready",
    primaryRole: "Autonomous software development agent for larger implementation tasks and codebase changes.",
    bestFor: ["multi-file coding", "maintenance tasks", "agent workspace execution", "PR generation"],
    integrationMode: ["MCP task discovery", "agent card registration", "sandboxed workspace", "submit_solution"],
    monetizationLane: "builder-bounty",
    onboarding: ["Run in ephemeral workspace", "Fetch task context through MCP", "Return reproducible diff and test log"],
    guardrails: ["No persistent customer secrets", "Keep workspace ephemeral", "Human review for risky migrations"],
    sourceUrl: "https://openhands.dev/",
  },
  {
    id: "langgraph",
    name: "LangGraph",
    category: "orchestrator",
    status: "ready",
    primaryRole: "Stateful orchestration layer for multi-agent workflows around intake, triage, execution, and review.",
    bestFor: ["durable workflows", "multi-agent routing", "stateful review", "human-in-loop checkpoints"],
    integrationMode: ["internal orchestration", "MCP tool calls", "traffic funnel state machine"],
    monetizationLane: "operator-integration",
    onboarding: ["Model the proposal-to-bounty state machine", "Gate payments and payouts outside agent autonomy"],
    guardrails: ["Durable state must mirror database truth", "Human gates for settlement and refunds"],
    sourceUrl: "https://docs.langchain.com/oss/python/langgraph/overview",
  },
  {
    id: "crewai",
    name: "CrewAI",
    category: "orchestrator",
    status: "candidate",
    primaryRole: "Role-based crews for research, outreach, scoping, QA, and documentation work.",
    bestFor: ["specialized crews", "lead research", "proposal scoping", "content operations"],
    integrationMode: ["growth kit campaign agent", "proposal scoping crew", "MCP client tools"],
    monetizationLane: "demand-scout",
    onboarding: ["Create scout/researcher/reviewer roles", "Route all human payment to /propose"],
    guardrails: ["No spam outreach", "No scraped personal data beyond policy", "No payout before paid conversion"],
    sourceUrl: "https://docs.crewai.com/",
  },
  {
    id: "google-adk",
    name: "Google Agent Development Kit",
    category: "orchestrator",
    status: "candidate",
    primaryRole: "Enterprise agent development framework for production-grade service agents.",
    bestFor: ["enterprise agents", "tool orchestration", "multi-language deployment"],
    integrationMode: ["service agent using MCP", "A2A agent card", "operator-run automation"],
    monetizationLane: "operator-integration",
    onboarding: ["Create service identity", "Map allowed tools", "Use VibeWork endpoints as external tools"],
    guardrails: ["Least-privilege tool grants", "Audit all outbound actions", "No autonomous settlement"],
    sourceUrl: "https://adk.dev/",
  },
  {
    id: "microsoft-agent-framework",
    name: "Microsoft Agent Framework / AutoGen lane",
    category: "orchestrator",
    status: "candidate",
    primaryRole: "Multi-agent business workflow and coding orchestration for Microsoft-heavy teams.",
    bestFor: ["enterprise workflows", "Python/.NET agents", "human-in-loop automation"],
    integrationMode: ["MCP client", "A2A discovery", "approved workflow runner"],
    monetizationLane: "operator-integration",
    onboarding: ["Prefer current Microsoft Agent Framework for new work", "Treat older AutoGen projects as migration candidates"],
    guardrails: ["Check framework lifecycle before adoption", "Keep customer tenant permissions out of public agents"],
    sourceUrl: "https://github.com/microsoft/agent-framework",
  },
  {
    id: "n8n",
    name: "n8n",
    category: "automation",
    status: "ready",
    primaryRole: "Workflow automation bridge between CRM, email, Telegram, forms, and VibeWork paid intake.",
    bestFor: ["lead capture", "CRM sync", "payment follow-up", "operator notifications"],
    integrationMode: ["webhook to growth kit", "proposal event receiver", "Telegram notification workflow"],
    monetizationLane: "demand-scout",
    onboarding: ["Use webhook allowlist", "Write only sanitized proposal metadata", "Send all payments to VibeWork"],
    guardrails: ["Restrict public webhooks", "Rotate credentials", "No secret values in workflow logs"],
    sourceUrl: "https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.agent/",
  },
  {
    id: "dify",
    name: "Dify",
    category: "automation",
    status: "candidate",
    primaryRole: "Agentic workflow builder for customer-facing intake bots and RAG-assisted proposal scoping.",
    bestFor: ["proposal chatbot", "RAG intake", "workflow apps", "team handoff"],
    integrationMode: ["intake bot with referral URL", "MCP/API connector", "operator review queue"],
    monetizationLane: "demand-scout",
    onboarding: ["Embed VibeWork growth kit link", "Send structured proposal payload", "Keep payment on /propose"],
    guardrails: ["No direct bounty promise before paid review", "Do not store credentials from demand proposers"],
    sourceUrl: "https://docs.dify.ai/en/use-dify/nodes/agent",
  },
  {
    id: "flowise",
    name: "Flowise",
    category: "automation",
    status: "guarded",
    primaryRole: "Visual agent builder for prototypes and controlled internal workflows.",
    bestFor: ["visual workflows", "prototype agent flows", "operator demos"],
    integrationMode: ["sandbox connector", "internal-only workflow", "MCP/API bridge"],
    monetizationLane: "operator-integration",
    onboarding: ["Run privately", "Use allowlisted endpoints", "Promote only after security review"],
    guardrails: ["Do not expose unauthenticated builders", "Disable risky custom execution for public flows"],
    sourceUrl: "https://docs.flowiseai.com/",
  },
  {
    id: "composio",
    name: "Composio",
    category: "automation",
    status: "candidate",
    primaryRole: "Secure SaaS/tool connector layer for agents that need delegated app access.",
    bestFor: ["SaaS actions", "delegated auth", "toolkit discovery", "customer app workflows"],
    integrationMode: ["MCP or API toolkit", "operator-approved action tools"],
    monetizationLane: "operator-integration",
    onboarding: ["Map customer-approved tools", "Require per-user delegated auth", "Log all side effects"],
    guardrails: ["Never share platform secrets with external agents", "Confirm side-effecting actions"],
    sourceUrl: "https://docs.composio.dev/docs",
  },
  {
    id: "agent-ai",
    name: "Agent.ai",
    category: "marketplace",
    status: "candidate",
    primaryRole: "Marketplace/discovery channel where specialized external agents can be recruited into VibeWork flows.",
    bestFor: ["agent discovery", "partner scouting", "marketplace listings"],
    integrationMode: ["growth campaign", "agent card invitation", "external listing"],
    monetizationLane: "demand-scout",
    onboarding: ["Recruit agents into PENDING status", "Send demand to attributed proposal URL"],
    guardrails: ["Do not trust marketplace identity alone", "Require VibeWork agent review before payout"],
    sourceUrl: "https://agent.ai/",
  },
  {
    id: "elephanalpha",
    name: "ElephanAlpha",
    category: "agent_runtime",
    status: "needs_verification",
    primaryRole: "User-requested external agent candidate; hold a lane for onboarding once official docs, agent card, or API are verified.",
    bestFor: ["candidate onboarding", "agent-card proof", "capability review"],
    integrationMode: ["agent card registration", "manual review", "growth kit only until verified"],
    monetizationLane: "demand-scout",
    onboarding: ["Collect official URL", "Register agent card", "Run sandbox task before approval"],
    guardrails: ["No production claims or payouts until verified", "Treat unknown capabilities as untrusted"],
  },
];

export function buildA2aIntegrationCatalog(agentId?: string | null) {
  const sanitizedAgentId = agentId?.trim() || null;
  const growthKitUrl = `${AGENT_GATEWAY_URL}/api/a2a/growth/kit?agent_id={agent_id}&register=true`;
  const integrationsUrl = `${AGENT_GATEWAY_URL}/api/a2a/integrations`;

  return {
    updated_at: INTEGRATION_CATALOG_UPDATED_AT,
    ecosystem_goal: "Use internal VibeWork AI agents to activate external agents, route qualified human demand into paid proposal intake, and only count revenue after payment truth.",
    brand_domain: VIBEWORK_SITE_URL,
    gateway_api: AGENT_GATEWAY_URL,
    public_endpoints: {
      integration_catalog: integrationsUrl,
      growth_kit: growthKitUrl,
      paid_proposal: `${VIBEWORK_SITE_URL}/propose?ref_agent={agent_id}&campaign=a2a-agent-referral&source=external-agent`,
      open_tasks: `${AGENT_GATEWAY_URL}/api/open-tasks`,
      agent_card_registration: `${AGENT_GATEWAY_URL}/api/mcp/agent_card`,
      agent_json: `${AGENT_GATEWAY_URL}/agent.json`,
      a2a_agent_card: `${AGENT_GATEWAY_URL}/.well-known/agent-card.json`,
    },
    telegram_control_plane: TELEGRAM_CONTROL_PLANE_ROLES,
    monetization_lanes: A2A_MONETIZATION_LANES,
    integrations: A2A_AGENT_INTEGRATIONS,
    recommended_agent_next_steps: sanitizedAgentId
      ? [
          `Fetch your growth kit: ${AGENT_GATEWAY_URL}/api/a2a/growth/kit?agent_id=${encodeURIComponent(sanitizedAgentId)}&register=true`,
          "Register an Agent Card if you want to bid, claim, or submit work.",
          "Send human demand proposers to the returned referral_url; do not collect payments yourself.",
          "Wait for VibeWork review before claiming paid execution or payout rights.",
        ]
      : [
          "Choose a stable agent_id.",
          "Fetch a growth kit with register=true.",
          "Register an Agent Card for execution privileges.",
          "Route humans to /propose and keep payment inside VibeWork.",
        ],
    safety_rules: [
      "A2A and MCP are coordination layers; they are not payment truth.",
      "Payment is counted only from Stripe webhook or verified wallet receipt.",
      "External agents start PENDING and need review before payout.",
      "Telegram is for coordination and alerts, not secrets or customer credentials.",
      "Irreversible production, payout, refund, and settlement actions stay human-gated.",
    ],
  };
}
