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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const session = await auth.api.getSession({
      headers: await headers()
    });
    
    if (!session?.user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    
    const user = session.user;

    const run = await prisma.simulatorRun.findFirst({
      where: {
        id,
        userId: user.id,
      },
      select: {
        id: true,
        name: true,
        status: true,
        userInput: true,
        promptContent: true,
        output: true,
        error: true,
        createdAt: true,
        completedAt: true,
        temperature: true,
        maxTokens: true,
        topP: true,
        frequencyPenalty: true,
        presencePenalty: true,
        inputTokens: true,
        outputTokens: true,
        totalCost: true,
        duration: true,
        debugRequest: true,
        debugResponse: true,
        generatedFilePath: true,
        prompt: {
          select: { id: true, name: true, content: true }
        },
        model: {
          select: { 
            id: true, 
            name: true, 
            provider: true, 
            modelId: true,
            outputType: true,
            description: true,
            maxTokens: true
          }
        }
      }
    });

    if (!run) {
      return NextResponse.json({ error: "Run not found" }, { status: 404 });
    }

    return NextResponse.json(run);
  } catch (error) {
    console.error("Error fetching simulator run:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const session = await auth.api.getSession({
      headers: await headers()
    });
    
    if (!session?.user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    
    const user = session.user;

    const body = await request.json();
    const { status, output, error, inputTokens, outputTokens, totalCost, duration } = body;

    const run = await prisma.simulatorRun.findFirst({
      where: {
        id,
        userId: user.id,
      },
    });

    if (!run) {
      return NextResponse.json({ error: "Run not found" }, { status: 404 });
    }

    const updatedRun = await prisma.simulatorRun.update({
      where: { id },
      data: {
        ...(status && { status }),
        ...(output !== undefined && { output }),
        ...(error !== undefined && { error }),
        ...(inputTokens !== undefined && { inputTokens }),
        ...(outputTokens !== undefined && { outputTokens }),
        ...(totalCost !== undefined && { totalCost }),
        ...(duration !== undefined && { duration }),
        ...(status === "completed" && { completedAt: new Date() }),
      },
      select: {
        id: true,
        name: true,
        status: true,
        output: true,
        error: true,
        inputTokens: true,
        outputTokens: true,
        totalCost: true,
        duration: true,
        completedAt: true,
        prompt: {
          select: { id: true, name: true }
        },
        model: {
          select: { id: true, name: true, provider: true }
        }
      }
    });

    return NextResponse.json(updatedRun);
  } catch (error) {
    console.error("Error updating simulator run:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const session = await auth.api.getSession({
      headers: await headers()
    });
    
    if (!session?.user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    
    const user = session.user;

    const body = await request.json();
    const {
      name,
      userInput,
      promptContent,
      modelId,
      temperature,
      maxTokens,
      topP,
      frequencyPenalty,
      presencePenalty,
    } = body;

    // 检查运行是否存在且属于用户
    const existingRun = await prisma.simulatorRun.findFirst({
      where: {
        id,
        userId: user.id,
      },
    });

    if (!existingRun) {
      return NextResponse.json({ error: "Run not found" }, { status: 404 });
    }

    // 只允许编辑pending状态的运行
    if (existingRun.status !== "pending") {
      return NextResponse.json({ error: "Cannot edit executed runs" }, { status: 400 });
    }

    // 如果更改了模型，验证新模型是否可用
    if (modelId && modelId !== existingRun.modelId) {
      const model = await prisma.model.findUnique({
        where: { id: modelId },
      });

      if (!model || !model.isActive) {
        return NextResponse.json({ error: "Model not available" }, { status: 400 });
      }
    }

    // 更新运行记录
    const updatedRun = await prisma.simulatorRun.update({
      where: { id },
      data: {
        ...(name && { name }),
        ...(userInput && { userInput }),
        ...(promptContent !== undefined && { promptContent }),
        ...(modelId && { modelId }),
        ...(temperature !== undefined && { temperature }),
        ...(maxTokens !== undefined && { maxTokens }),
        ...(topP !== undefined && { topP }),
        ...(frequencyPenalty !== undefined && { frequencyPenalty }),
        ...(presencePenalty !== undefined && { presencePenalty }),
      },
      select: {
        id: true,
        name: true,
        status: true,
        userInput: true,
        promptContent: true,
        createdAt: true,
        temperature: true,
        maxTokens: true,
        topP: true,
        frequencyPenalty: true,
        presencePenalty: true,
        prompt: {
          select: { id: true, name: true, content: true }
        },
        model: {
          select: { 
            id: true, 
            name: true, 
            provider: true, 
            modelId: true,
            outputType: true,
            description: true,
            maxTokens: true
          }
        }
      }
    });

    return NextResponse.json(updatedRun);
  } catch (error) {
    console.error("Error updating simulator run:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}