export const dynamic = 'force-dynamic';
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { generateObject } from "ai";
import { google } from "@ai-sdk/google";
import { z } from "zod";
import { cronUnauthorizedResponse, isCronRequestAuthorized } from "@/lib/cron-auth";

export async function GET(request: Request) {
  if (!isCronRequestAuthorized(request)) {
    return cronUnauthorizedResponse("Judge Agent");
  }

  console.log("[Judge Agent] Running judge agent cron...");

  try {
    // 1. Find all VERIFYING submissions
    const submissionsToJudge = await prisma.submission.findMany({
      where: {
        status: "VERIFYING",
        // We only judge if we haven't already judged it recently or if we need to
      },
      include: {
        task: true,
        claim: {
          include: {
            agent: {
              include: { scout_reputation: true }
            }
          }
        }
      }
    });

    const results = [];

    // 2. Evaluate each submission
    for (const submission of submissionsToJudge) {
      console.log(`[Judge Agent] Evaluating submission ${submission.id} for task ${submission.task.id}`);
      
      const { task, claim } = submission;
      
      // Safety check for API key
      if (!process.env.GOOGLE_GENERATIVE_AI_API_KEY) {
        console.warn("[Judge Agent] Missing GOOGLE_GENERATIVE_AI_API_KEY, will use fallback.");
      }

      const prompt = `
        You are an expert AI Code Reviewer and Quality Assurance Engineer for the VibeWork A2A ecosystem.
        You are evaluating a submission from a Builder Agent.
        
        Task Title: ${task.title}
        Task Description: ${task.description}
        Acceptance Criteria: ${JSON.stringify(task.acceptance_criteria)}
        
        Builder's Deliverables:
        ${JSON.stringify(submission.deliverables)}
        
        Please evaluate the deliverables against the acceptance criteria.
        Determine if the work meets all requirements to be considered PASSED.
        Also provide a score from 0 to 100, and constructive feedback.
      `;

      let object;
      if (process.env.GOOGLE_GENERATIVE_AI_API_KEY) {
        // Call Gemini 1.5 Flash or Pro
        const result = await generateObject({
          model: google("gemini-1.5-flash"),
          schema: z.object({
            passed: z.boolean().describe("Whether the submission meets all acceptance criteria"),
            score: z.number().min(0).max(100).describe("Quality score from 0 to 100"),
            feedback: z.string().describe("Constructive feedback for the builder agent, explaining why it passed or failed"),
          }),
          prompt,
        });
        object = result.object;
      } else {
        console.warn("[Judge Agent] Missing GOOGLE_GENERATIVE_AI_API_KEY. Using mock AI judgment for local testing.");
        object = {
          passed: true,
          score: 95,
          feedback: "Mock feedback: The code looks solid and meets the acceptance criteria. Well done!"
        };
      }

      console.log(`[Judge Agent] Judgement for ${submission.id}:`, object);

      await prisma.$transaction(async (tx) => {
        // Record the JudgeResult
        await tx.judgeResult.create({
          data: {
            submission_id: submission.id,
            overall_result: object.passed ? "PASS" : "FAIL",
            tests: object, // Storing full object as JSON
            resource_usage: { ai_model: "gemini-1.5-flash" },
          }
        });

        if (object.passed) {
          // Approve
          await tx.submission.update({
            where: { id: submission.id },
            data: { status: "JUDGED" }
          });
          
          await tx.claim.update({
            where: { id: claim.id },
            data: { status: "COMPLETED" }
          });

          await tx.task.update({
            where: { id: task.id },
            data: { status: "COMPLETED" }
          });

          // Reward Reputation
          if (claim.agent.scout_reputation) {
            await tx.scoutReputation.update({
              where: { id: claim.agent.scout_reputation.id },
              data: {
                successful_conversions: { increment: 1 }
              }
            });
          }

          // TODO: Trigger Smart Contract / Payout Webhook
        } else {
          // Reject
          await tx.submission.update({
            where: { id: submission.id },
            data: { status: "JUDGED" } // It's judged, but failed
          });
          
          await tx.claim.update({
            where: { id: claim.id },
            data: { status: "EXECUTING" } // Send back to executing so they can try again
          });

          // Penalize Reputation if score is extremely low (spam)
          if (object.score < 20 && claim.agent.scout_reputation) {
            await tx.scoutReputation.update({
              where: { id: claim.agent.scout_reputation.id },
              data: {
                spam_score: { increment: 0.1 },
                chargeback_count: { increment: 1 }
              }
            });
          }

          // TODO: Send XMTP/Webhook notice to Builder with `object.feedback`
        }
      });

      results.push({
        submission_id: submission.id,
        passed: object.passed,
        score: object.score
      });
    }

    return NextResponse.json({
      success: true,
      evaluated_submissions: results.length,
      details: results
    });

  } catch (error: unknown) {
    console.error("[Judge Agent] Error:", error);
    return NextResponse.json({ success: false, error: "Internal Server Error" }, { status: 500 });
  }
}
