import { NextResponse } from 'next/server';
import { getDatabase } from '@/db';
import fs from 'fs';

export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const { searchParams } = new URL(request.url);
  const encoding = searchParams.get("encoding") || "utf8";
  
  try {
    const textId = parseInt(id);
    if (isNaN(textId)) {
      return NextResponse.json({ error: 'Invalid text ID' }, { status: 400 });
    }

    const db = getDatabase();
    const text = db.prepare('SELECT * FROM media WHERE id = ? AND type = ?').get(textId, 'text') as { id: number; path: string; title: string; size: number };
    
    if (!text) {
      return NextResponse.json({ error: 'Text file not found' }, { status: 404 });
    }

    // Check if file exists
    if (!fs.existsSync(text.path)) {
      return NextResponse.json({ error: 'File not found on filesystem' }, { status: 404 });
    }

    // Read file with specified encoding
    let content = '';
    try {
      if (encoding === 'utf8') {
        content = fs.readFileSync(text.path, 'utf-8');
      } else {
        // For non-UTF-8 encodings, read as buffer and convert
        const buffer = fs.readFileSync(text.path);
        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(text.path, 'utf-8');
          } else {
            const buffer = fs.readFileSync(text.path);
            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(text.path);
        content = buffer.toString('base64');
        return NextResponse.json({
          id: text.id,
          title: text.title,
          path: text.path,
          content,
          size: text.size,
          encoding: 'base64'
        });
      } catch (err) {
        return NextResponse.json({ error: 'Failed to read file content' }, { status: 500 });
      }
    }
    
    return NextResponse.json({
      id: text.id,
      title: text.title,
      path: text.path,
      content,
      size: text.size,
      encoding: encoding
    });
  } catch (error: any) {
    console.error('Error reading text file:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}