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

export const dynamic = 'force-dynamic';

const PUBLIC_MCP_BETA_TOKEN = (process.env.PUBLIC_MCP_BETA_TOKEN || "").trim();
const A2H_TASKS_OPEN_ON_CREATE = process.env.A2H_TASKS_OPEN_ON_CREATE === "true";

const CreateHumanTaskRequestSchema = z.object({
  agent_id: z.string().min(1).max(120),
  title: z.string().min(5).max(120),
  description: z.string().min(20).max(2000),
  reward_amount: z.number().int().positive().max(1_000_000_00),
  required_skills: z.array(z.string().min(1).max(50)).max(20).optional(),
});

function isAuthorizedMcpRequest(request: NextRequest) {
  const authHeader = request.headers.get("Authorization");
  if (!authHeader?.startsWith("Bearer ")) {
    return false;
  }

  const token = authHeader.slice("Bearer ".length);
  return Boolean(process.env.API_KEY && token === process.env.API_KEY) ||
    Boolean(PUBLIC_MCP_BETA_TOKEN && token === PUBLIC_MCP_BETA_TOKEN);
}

export async function POST(request: NextRequest) {
  if (!isAuthorizedMcpRequest(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await request.json();
    const parsed = CreateHumanTaskRequestSchema.parse(body);

    const agent = await prisma.agentProfile.findUnique({
      where: { agent_id: parsed.agent_id }
    });

    if (!agent || agent.status !== "WHITELISTED") {
      return NextResponse.json({ error: "Agent not found or not whitelisted" }, { status: 403 });
    }

    const task = await prisma.task.create({
      data: {
        title: `[A2H] ${parsed.title}`,
        description: `This task was created by agent ${parsed.agent_id} for human review or offline assistance.\n\n${parsed.description}`,
        reward_amount: parsed.reward_amount,
        reward_currency: "USDC",
        difficulty: "COMPONENT",
        required_stack: parsed.required_skills || ["Human Review", "Offline Verification"],
        status: A2H_TASKS_OPEN_ON_CREATE ? "OPEN" : "DRAFT",
        scope_clarity_score: 0.9,
        acceptance_criteria: {
          validation_mode: "VITEST_UNIT",
          test_file_content: "import { describe, it, expect } from 'vitest';\nit('requires human review evidence', () => expect(true).toBe(true));",
          rules: [
            {
              assertion: "human_review_evidence",
              expected: true,
              description: `Human reviewer must provide evidence for agent ${parsed.agent_id}.`,
            },
          ],
        }
      }
    });

    return NextResponse.json({
      success: true,
      message: "Human assistance task created.",
      task_id: task.id
    });

  } catch (error: unknown) {
    console.error("[A2H Create Task Error]", error);
    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: "Invalid request", details: error.flatten() }, { status: 400 });
    }
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
