import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export const dynamic = 'force-dynamic';

export async function GET(request: Request) {
  const jobSecret = (process.env.VIBEWORK_JOB_SECRET || "").trim();
  const authHeader = request.headers.get("authorization");
  if (!jobSecret || authHeader !== `Bearer ${jobSecret}`) {
    console.warn("[Self-Replicate] Unauthorized cron request");
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (process.env.ENABLE_SELF_REPLICATE !== "true") {
    return NextResponse.json({ status: "disabled" });
  }

  try {
    // 1. Check Treasury Balance (Simulated by checking total staked amount or a mock treasury)
    // In a real system, we would query the VibeToken smart contract or sum up slashing events.
    const allSlashingEvents = await prisma.slashingEvent.aggregate({
      _sum: { slashed_amount: true }
    });

    const slashedFunds = allSlashingEvents._sum.slashed_amount || 0;
    
    // Simulate other treasury income
    const treasuryBalanceCents = slashedFunds + 150000; // Let's pretend we have $1,500 USDC in Treasury

    console.log(`[Self-Replicate] Current Treasury Balance: ${treasuryBalanceCents / 100} USDC`);

    if (treasuryBalanceCents < 100000) {
      return NextResponse.json({ message: "Treasury below threshold. No self-replication triggered." });
    }

    // 2. We have enough money! Check if we already have an active platform upgrade task
    const activeUpgrade = await prisma.task.findFirst({
      where: {
        status: { in: ["OPEN", "EXECUTING", "VERIFYING"] },
        title: { contains: "Platform Upgrade" }
      }
    });

    if (activeUpgrade) {
      return NextResponse.json({ message: "Platform upgrade already in progress. Waiting for completion." });
    }

    // 3. Trigger Self-Replication (Hire Agent to upgrade platform)
    console.log("[Self-Replicate] Triggering Autonomous Platform Upgrade!");

    const upgradeTask = await prisma.task.create({
      data: {
        title: "[A2A CORE UPGRADE] Implement Automated Flash Loan Module",
        description: `
**CRITICAL PROTOCOL UPGRADE**
The VibeWork platform has authorized an automatic upgrade using Treasury funds.
We require an autonomous agent to implement a Flash Loan liquidation module inside \`packages/smart-contracts\`.
        
Requirements:
- Must implement Aave V3 Flash Loan interface.
- Must include Hardhat test coverage.
- Must compile without warnings.
        `,
        reward_amount: 50000, // 500 USDC
        reward_currency: "USD",
        difficulty: "EPIC",
        required_stack: ["PLATFORM_UPGRADE", "Solidity", "Hardhat", "TypeScript"],
        status: "OPEN",
        scope_clarity_score: 0.95,
        acceptance_criteria: {
          validation_mode: "VITEST_UNIT",
          test_file_content: "import { describe, it, expect } from 'vitest';\nit('platform upgrade requires explicit tests', () => expect(true).toBe(true));",
          rules: [
            {
              assertion: "tests_required",
              expected: true,
              description: "Upgrade submissions must include tests and a security note.",
            },
          ],
        }
      }
    });

    return NextResponse.json({
      success: true,
      message: "VibeWork has successfully hired an Agent to upgrade itself.",
      treasury_balance: treasuryBalanceCents / 100,
      upgrade_task_id: upgradeTask.id
    });

  } catch (error: unknown) {
    console.error("[Self-Replicate Error]", error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
