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

const STORAGE_DIR = path.join(process.cwd(), "data", "agent-outputs");

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

function getAgentDir(agent: string) {
  const dir = path.join(STORAGE_DIR, agent);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
  return dir;
}

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const agent = searchParams.get("agent");
  const date = searchParams.get("date");
  
  if (!agent) {
    // Return list of all agent directories
    ensureDir();
    const agents = fs.readdirSync(STORAGE_DIR).filter(f => 
      fs.statSync(path.join(STORAGE_DIR, f)).isDirectory()
    );
    return NextResponse.json(agents);
  }
  
  const agentDir = getAgentDir(agent);
  
  if (date) {
    // Return specific file
    const file = path.join(agentDir, `${date}.md`);
    if (fs.existsSync(file)) {
      const content = fs.readFileSync(file, "utf-8");
      return NextResponse.json({ agent, date, content });
    }
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
  
  // Return list of files for agent
  const files = fs.readdirSync(agentDir)
    .filter(f => f.endsWith('.md'))
    .map(f => f.replace('.md', ''))
    .sort()
    .reverse();
  
  return NextResponse.json(files);
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, agent, date, content } = body;
    
    if (action === "save") {
      const agentDir = getAgentDir(agent);
      const file = path.join(agentDir, `${date}.md`);
      fs.writeFileSync(file, content);
      return NextResponse.json({ success: true, file });
    }
    
    if (action === "delete") {
      const agentDir = getAgentDir(agent);
      const file = path.join(agentDir, `${date}.md`);
      if (fs.existsSync(file)) {
        fs.unlinkSync(file);
      }
      return NextResponse.json({ success: true });
    }
    
    return NextResponse.json({ error: "Invalid action" }, { status: 400 });
    
  } catch (error) {
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
