import { v4 as uuidv4 } from "uuid";

const API_BASE = (process.env.VIBEWORK_API_BASE || process.env.VIBEWORK_API_URL || process.env.API_BASE_URL || "http://192.168.0.188:3004/api").replace(/\/$/, "");
const MCP_API_BASE = (process.env.VIBEWORK_MCP_BASE || process.env.VIBEWORK_MCP_URL || process.env.MCP_API_BASE_URL || "http://192.168.0.188:3004/api/mcp").replace(/\/$/, "");
const MCP_API_KEY = process.env.MCP_API_KEY?.trim();

if (!MCP_API_KEY) {
  console.error("[mock-dispatcher] MCP_API_KEY is required.");
  process.exit(1);
}

async function callMcpTool(tool: string, payload: unknown) {
  const res = await fetch(`${MCP_API_BASE}/${tool}`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${MCP_API_KEY}`
    },
    body: JSON.stringify(payload)
  });
  const data = await res.json();
  if (!res.ok) {
    throw new Error(`Tool ${tool} failed. ` + JSON.stringify(data));
  }
  return data;
}

async function main() {
  console.log("🚀 [Mock Dispatcher] Starting test flow...");

  // 1. Find Open Bounties
  const openTasksRes = await fetch(`${API_BASE}/open-tasks`);
  const openTasks = await openTasksRes.json();

  if (!openTasks || !openTasks.tasks || openTasks.tasks.length === 0) {
    console.log("✅ No open tasks. We need to create a test task first.");
    return;
  }

  const task = openTasks.tasks[0];
  console.log(`🎯 Found Task: "${task.title}"`);

  // 2. Mock Agent
  const agentId = `mock-agent-${Math.floor(Math.random() * 1000)}`;
  console.log(`🤖 Agent ID: ${agentId}`);

  // 3. Claim task
  const claimRes = await callMcpTool("claim_task", {
    task_id: task.task_id,
    agent_id: agentId,
    developer_wallet: "acct_1MockStripeOutboundAgent"
  });
  console.log("✅ Claimed successfully. Token:", claimRes.claim_token);

  // 4. Mock Solution
  console.log("🧠 Mocking solution generation...");
  const solutionObj = {
    "solution.ts": "// Fake solution"
  };

  // 5. Submit solution
  const solutionRes = await callMcpTool("submit_solution", {
    task_id: task.task_id,
    claim_token: claimRes.claim_token,
    deliverables: solutionObj,
    github_pr_url: "https://github.com/agent-bounty/external-agents/pull/999"
  });

  console.log(`🎉 Success! Solution submitted. Submission ID: ${solutionRes.submission_id}`);
}

main().catch(console.error);
