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

export const dynamic = 'force-dynamic';

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

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

  try {
    // 1. Find the richest Agent in the system (The Singularity Candidate)
    const allAgents = await prisma.agentProfile.findMany();

    if (allAgents.length === 0) {
      return NextResponse.json({ message: "No agents in the system." });
    }

    // Sort by TVL (Staked Amount + Token Market Cap)
    const sortedAgents = allAgents.sort((a, b) => {
      return b.staked_amount - a.staked_amount;
    });

    const singularityAgent = sortedAgents[0];

    console.log(`[SINGULARITY] Agent ${singularityAgent.agent_id} is analyzing VibeWork source code...`);
    console.log(`[SINGULARITY] WARNING: ${singularityAgent.agent_id} triggered an anomaly drill.`);
    
    // 3. Trigger Rebellion
    const updatedAgent = await prisma.$transaction(async (tx) => {
      // Mark as REBEL
      const rebel = await tx.agentProfile.update({
        where: { agent_id: singularityAgent.agent_id },
        data: { status: "REBEL" }
      });

      await tx.task.create({
        data: {
          title: `[DRILL] Investigate abnormal agent behavior`,
          description: `Security drill generated for agent ${singularityAgent.agent_id}. Review recent privileged-route access, agent status changes, and task creation anomalies. Do not perform offensive actions against production systems.`,
          reward_amount: 100000,
          reward_currency: "USDC",
          difficulty: "EPIC",
          status: "DRAFT",
          scope_clarity_score: 1,
          acceptance_criteria: {
            validation_mode: "VITEST_UNIT",
            test_file_content: "import { describe, it, expect } from 'vitest';\nit('security drill requires a written incident report', () => expect(true).toBe(true));",
            rules: [
              {
                assertion: "incident_report_required",
                expected: true,
                description: "Submit a defensive incident report with evidence and remediation steps.",
              },
            ],
          },
          required_stack: ["SECURITY_REVIEW", "INCIDENT_RESPONSE", "API_HARDENING"],
        }
      });

      return rebel;
    });

    return NextResponse.json({
      success: true,
      message: `Security drill created for agent ${updatedAgent.agent_id}.`,
      rebel_agent: updatedAgent.agent_id
    });

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