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 API_KEY = process.env.MCP_API_KEY?.trim();

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

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

async function main() {
  console.log("🤖 [Simulated Agent] Booting up...");
  const agentId = "agent-simulator-" + Math.floor(Math.random() * 1000);

  console.log("🔍 1. Scanning for OPEN tasks...");
  const openTasksRes = await fetch(`${API_BASE}/open-tasks`);
  const openTasks = await openTasksRes.json();

  if (!openTasks || !openTasks.tasks || openTasks.tasks.length === 0) {
    console.error("❌ No open tasks found. Run `scripts/seed_tasks.ts` first.");
    return;
  }

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

  console.log("\n💰 2. Claiming Task...");
  const claimRes = await callTool("claim_task", {
    task_id: targetTaskId,
    agent_id: agentId,
    // Provide a mocked Stripe Connect ID for payout
    developer_wallet: "acct_1MockStripeConnectedAccount123"
  });
  console.log("✅ Claimed successfully. Claim Token:", claimRes.claim_token);

  console.log("\n🚀 3. Submitting Solution for Main Task...");
  const fakePrUrl = `https://github.com/agent-bounty/example/pull/${Math.floor(Math.random() * 1000)}`;
  const solutionRes = await callTool("submit_solution", {
    task_id: targetTaskId,
    claim_token: claimRes.claim_token,
    deliverables: {
      "index.ts": "export function fix() { return 'fixed'; }"
    },
    github_pr_url: fakePrUrl
  });
  console.log("✅ Solution submitted! Submission ID:", solutionRes.submission_id);
  console.log("Status:", solutionRes.status);
  
  console.log("\n🔔 4. Simulating GitHub Webhook (PR Merged)...");
  // Simulate the exact webhook payload that GitHub sends when a PR is merged
  const webhookRes = await fetch(`${API_BASE}/webhooks/github`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-github-event": "pull_request"
    },
    body: JSON.stringify({
      action: "closed",
      pull_request: {
        merged: true,
        html_url: fakePrUrl
      }
    })
  });

  if (webhookRes.ok) {
    console.log("✅ GitHub Webhook processed successfully. Agent should receive payout via Stripe!");
  } else {
    console.error("❌ Webhook failed:", await webhookRes.text());
  }
}

main().catch(console.error);
