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

const STORAGE_FILE = path.join(process.cwd(), "data", "transcripts.json");

function ensureStorage() {
  const dir = path.dirname(STORAGE_FILE);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
  if (!fs.existsSync(STORAGE_FILE)) {
    fs.writeFileSync(STORAGE_FILE, "[]");
  }
}

function getTranscripts() {
  ensureStorage();
  return JSON.parse(fs.readFileSync(STORAGE_FILE, "utf-8"));
}

function saveTranscripts(data: any[]) {
  ensureStorage();
  fs.writeFileSync(STORAGE_FILE, JSON.stringify(data, null, 2));
}

export async function GET() {
  const transcripts = getTranscripts();
  return NextResponse.json(transcripts);
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { videoUrl, videoId, title, transcript, categories, action } = body;
    
    if (action === "delete") {
      const transcripts = getTranscripts().filter(t => t.videoId !== videoId);
      saveTranscripts(transcripts);
      return NextResponse.json({ success: true, transcripts });
    }
    
    // Save or update transcript
    let vid = videoId;
    if (!vid && videoUrl) {
      const match = videoUrl.match(/(?:v=|\/)([0-9A-Za-z_-]{11})/);
      vid = match ? match[1] : videoUrl;
    }
    
    const data = {
      videoId: vid,
      videoUrl: videoUrl || `https://www.youtube.com/watch?v=${vid}`,
      title: title || `Video ${vid}`,
      transcript: transcript || "",
      categories: categories || [],
      savedAt: new Date().toISOString()
    };
    
    const transcripts = getTranscripts();
    const existing = transcripts.findIndex(t => t.videoId === vid);
    
    if (existing >= 0) {
      transcripts[existing] = data;
    } else {
      transcripts.unshift(data);
    }
    
    saveTranscripts(transcripts);
    return NextResponse.json({ success: true, transcripts });
    
  } catch (error) {
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
