import { NextRequest, NextResponse } from "next/server";
import fs from "fs";
import path from "path";

const STORAGE_DIR = path.join(process.cwd(), "data");
const LOGS_FILE = path.join(STORAGE_DIR, "execution-logs.json");
const OUTPUTS_FILE = path.join(STORAGE_DIR, "agent-outputs.json");

function ensureDir() {
  if (!fs.existsSync(STORAGE_DIR)) {
    fs.mkdirSync(STORAGE_DIR, { recursive: true });
  }
}

function readJSON(file: string, defaultValue: any = []) {
  ensureDir();
  if (!fs.existsSync(file)) {
    fs.writeFileSync(file, JSON.stringify(defaultValue));
    return defaultValue;
  }
  try {
    return JSON.parse(fs.readFileSync(file, "utf-8"));
  } catch {
    return defaultValue;
  }
}

function writeJSON(file: string, data: any) {
  ensureDir();
  fs.writeFileSync(file, JSON.stringify(data, null, 2));
}

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const agent = searchParams.get("agent");
  const templateId = searchParams.get("templateId");
  const limit = parseInt(searchParams.get("limit") || "50");
  
  let logs = readJSON(LOGS_FILE, []);
  
  // Filter by agent
  if (agent) {
    logs = logs.filter((l: any) => l.agent === agent);
  }
  
  // Filter by template
  if (templateId) {
    logs = logs.filter((l: any) => l.templateId === templateId);
  }
  
  // Limit
  logs = logs.slice(0, limit);
  
  return NextResponse.json(logs);
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, logId, output, status, agent } = body;
    
    const logs = readJSON(LOGS_FILE, []);
    
    if (action === "update") {
      const idx = logs.findIndex((l: any) => l.id === logId);
      if (idx >= 0) {
        if (status) logs[idx].status = status;
        if (output) logs[idx].output = output;
        if (status === "completed" || status === "failed") {
          logs[idx].completedAt = new Date().toISOString();
        }
        writeJSON(LOGS_FILE, logs);
        return NextResponse.json({ success: true, log: logs[idx] });
      }
    }
    
    if (action === "clear") {
      // Clear old logs (keep last 100)
      const filtered = logs.slice(0, 100);
      writeJSON(LOGS_FILE, filtered);
      return NextResponse.json({ success: true, logs: filtered });
    }
    
    return NextResponse.json({ error: "Invalid action" }, { status: 400 });
    
  } catch (error) {
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
