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

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams
  const filePath = searchParams.get("path")

  if (!filePath) {
    return NextResponse.json({ error: "Path is required" }, { status: 400 })
  }

  if (filePath.startsWith("custom/")) {
    return NextResponse.json({ content: "", isCustom: true })
  }

  try {
    const normalizedPath = filePath.replace(/^\/+/, "")
    const fullPath = path.join(process.cwd(), normalizedPath)

    if (!fs.existsSync(fullPath)) {
      return NextResponse.json({ error: "File not found" }, { status: 404 })
    }

    const stats = fs.statSync(fullPath)
    if (stats.isDirectory()) {
      return NextResponse.json({ error: "Path is a directory" }, { status: 400 })
    }

    const content = fs.readFileSync(fullPath, "utf-8")
    return NextResponse.json({ content, isCustom: false })
  } catch (error) {
    console.error("[v0] Error reading file:", error)
    return NextResponse.json({ error: "Failed to read file" }, { status: 500 })
  }
}
