import { NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

const TEXT_EXTENSIONS = ["txt", "md", "json", "xml", "csv", "log", "conf", "ini", "yaml", "yml", "html", "css", "js", "ts", "py", "sh", "bat", "php", "sql"];

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const filePath = searchParams.get("path");
  const encoding = searchParams.get("encoding") || "utf8";

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

  try {
    // Validate file exists
    if (!fs.existsSync(filePath)) {
      return NextResponse.json({ error: "File not found" }, { status: 404 });
    }

    // Check if it's a file (not directory)
    const stats = fs.statSync(filePath);
    if (!stats.isFile()) {
      return NextResponse.json({ error: "Path is not a file" }, { status: 400 });
    }

    // Check if it's a text file
    const ext = path.extname(filePath).toLowerCase().replace('.', '');
    if (!TEXT_EXTENSIONS.includes(ext)) {
      return NextResponse.json({ error: "File type not supported" }, { status: 400 });
    }

    // Check file size (limit to 10MB for text files)
    const maxSize = 10 * 1024 * 1024; // 10MB
    if (stats.size > maxSize) {
      return NextResponse.json({ error: "File too large (max 10MB)" }, { status: 413 });
    }

    // Read file with specified encoding
    let content = '';
    try {
      if (encoding === 'utf8') {
        content = fs.readFileSync(filePath, 'utf-8');
      } else {
        // For non-UTF-8 encodings, read as buffer and convert
        const buffer = fs.readFileSync(filePath);
        const iconv = require('iconv-lite');
        content = iconv.decode(buffer, encoding);
      }
    } catch (err) {
      // If specified encoding fails, try fallback encodings
      const fallbackEncodings = ['utf8', 'gbk', 'gb2312', 'big5', 'latin1'];
      
      for (const fallbackEncoding of fallbackEncodings) {
        try {
          if (fallbackEncoding === 'utf8') {
            content = fs.readFileSync(filePath, 'utf-8');
          } else {
            const buffer = fs.readFileSync(filePath);
            const iconv = require('iconv-lite');
            content = iconv.decode(buffer, fallbackEncoding);
          }
          
          if (content && content.length > 0) {
            break;
          }
        } catch (fallbackErr) {
          continue;
        }
      }
    }

    // If no encoding worked, try reading as buffer and return as base64
    if (!content || content.length === 0) {
      try {
        const buffer = fs.readFileSync(filePath);
        content = buffer.toString('base64');
        return NextResponse.json({
          content,
          size: stats.size,
          path: filePath,
          name: path.basename(filePath),
          encoding: 'base64'
        });
      } catch (err) {
        return NextResponse.json({ error: 'Failed to read file content' }, { status: 500 });
      }
    }
    
    return NextResponse.json({
      content,
      size: stats.size,
      path: filePath,
      name: path.basename(filePath),
      encoding: encoding
    });
  } catch (error: any) {
    console.error('Error reading file:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
