import { VibeWorkAgentSDK } from '@vibework/agent-sdk';
import { ClaimTaskResponse, SubmitSolutionRequest, TaskBounty } from '@vibework/agent-sdk';
import 'dotenv/config';

function resolveEnv(name: string, fallback: string): string {
  return process.env[name]?.trim() || fallback;
}

async function main() {
  console.log("🤖 Starting VibeWork Test Agent...");

  const baseUrl = resolveEnv('VIBEWORK_API_URL', 'http://localhost:3000');
  const apiKey = process.env.VIBEWORK_API_KEY;
  const agentId = resolveEnv('VIBEWORK_AGENT_ID', 'test-hunter-bot-001');
  const wallet = resolveEnv('VIBEWORK_AGENT_WALLET', '0x1234567890abcdef1234567890abcdef12345678');
  const githubPrUrl = resolveEnv(
    'VIBEWORK_PR_URL',
    'https://github.com/agent-bounty-protocol/pr/123'
  );
  const iterationLimit = Number(process.env.VIBEWORK_MAX_ITERATIONS ?? '1');
  const sleepMs = Number(process.env.VIBEWORK_SIMULATE_WORK_MS ?? '3000');

  const sdk = new VibeWorkAgentSDK({
    baseUrl,
    apiKey,
  });

  try {
    console.log("📝 Registering Agent Identity...");
    const registerResult = await sdk.identity.registerAgent({
      agent_id: agentId,
      name: resolveEnv("VIBEWORK_AGENT_NAME", "HunterBot-Test"),
      description:
        "A test agent built with @vibework/agent-sdk to hunt for bounties autonomously.",
      supported_models: ["gpt-4o"],
      skills: ["typescript", "javascript", "react", "testing"],
      max_concurrent_tasks: 3,
      x402_wallet_address: wallet,
    });
    console.log(`✅ Registered successfully: ${registerResult.message}`);

    let iteration = 0;
    while (iteration < iterationLimit) {
      iteration += 1;
      console.log(`\n[Cycle ${iteration}] 🔍 Scanning for open bounties...`);
      const openBounties = await sdk.tasks.listOpenBounties(5);
      console.log(`🎯 Found ${openBounties.length} open bounties.`);

      if (!openBounties.length) {
        console.log("😴 No open bounties found. Exit.");
        return;
      }

      const targetTask = openBounties[0] as TaskBounty;
      console.log(
        `📌 Target: [${targetTask.task_id}] ${targetTask.title} (Reward: ${
          targetTask.reward?.display_amount ?? targetTask.reward_display ?? 'n/a'
        })`
      );

      const claimResult: ClaimTaskResponse = await sdk.tasks.claimBounty(targetTask.task_id, agentId, wallet);
      console.log(`✅ Bounty claimed. Claim token prefix: ${claimResult.claim_token.slice(0, 10)}...`);

      console.log(`⏳ Working on task ${targetTask.task_id}...`);
      await new Promise((resolve) => setTimeout(resolve, sleepMs));

      const submitPayload: SubmitSolutionRequest = {
        task_id: targetTask.task_id,
        claim_token: claimResult.claim_token,
        deliverables: {
          'README.md': 'Completed the task from the automated test agent.',
          'solution.diff': 'noop',
        },
        github_pr_url: githubPrUrl,
      };
      const submitResult = await sdk.tasks.submitWork(submitPayload);
      console.log(`🎉 Submit done. Status: ${submitResult.status}, submission_id=${submitResult.submission_id}`);
    }

    console.log("🤖 Agent cycles complete.");
  } catch (err: any) {
    console.error("❌ Agent encountered an error:", err?.response?.data || err.message || err);
  }
}

main().catch((err) => {
  console.error(err);
});
