import { NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import { getPostsDirectory } from '@/lib/postsDirectory';
import { spawnSync } from 'child_process';

const postsDirectory = getPostsDirectory();

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { title, date, tags, summary, content, path: folderPath } = body;

    // Create slug from title
    const slug = title
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)/g, '');

    // Create frontmatter
    const frontmatter = matter.stringify(content, {
      title,
      date,
      tags,
      summary,
      author: process.env.NEXT_PUBLIC_BLOG_OWNER + "'s" || 'Anonymous',
    });

    // Write the file in the correct folder if provided
    let filePath;
    if (folderPath && folderPath.trim() !== '') {
      filePath = path.join(postsDirectory, folderPath, `${slug}.md`);
      // Ensure the directory exists
      fs.mkdirSync(path.dirname(filePath), { recursive: true });
    } else {
      filePath = path.join(postsDirectory, `${slug}.md`);
    }
    fs.writeFileSync(filePath, frontmatter);

    return NextResponse.json({ success: true, slug });
  } catch (error) {
    console.error('Error creating post:', error);
    return NextResponse.json(
      { error: 'Error creating post' },
      { status: 500 }
    );
  }
}

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const info = searchParams.get('rsparseinfo');
  if (info === '1') {
    // Call the Rust backend for parser stats
    const rustResult = spawnSync(
      process.cwd() + '/markdown_backend/target/release/markdown_backend',
      ['rsparseinfo'],
      { encoding: 'utf-8' }
    );
    if (rustResult.status === 0 && rustResult.stdout) {
      return new Response(rustResult.stdout, {
        status: 200,
        headers: { 'Content-Type': 'application/json' },
      });
    } else {
      return new Response(JSON.stringify({ error: rustResult.stderr || rustResult.error }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' },
      });
    }
  }
  const checkhealth = searchParams.get('checkhealth');
  if (checkhealth === '1') {
    // Call the Rust backend for health check
    const rustResult = spawnSync(
      process.cwd() + '/markdown_backend/target/release/markdown_backend',
      ['checkhealth'],
      { encoding: 'utf-8' }
    );
    if (rustResult.status === 0 && rustResult.stdout) {
      return new Response(rustResult.stdout, {
        status: 200,
        headers: { 'Content-Type': 'application/json' },
      });
    } else {
      return new Response(JSON.stringify({ error: rustResult.stderr || rustResult.error }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' },
      });
    }
  }
  const logs = searchParams.get('logs');
  if (logs === '1') {
    // Call the Rust backend for parser logs
    const rustResult = spawnSync(
      process.cwd() + '/markdown_backend/target/release/markdown_backend',
      ['logs'],
      { encoding: 'utf-8' }
    );
    if (rustResult.status === 0 && rustResult.stdout) {
      return new Response(rustResult.stdout, {
        status: 200,
        headers: { 'Content-Type': 'application/json' },
      });
    } else {
      return new Response(JSON.stringify({ error: rustResult.stderr || rustResult.error }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' },
      });
    }
  }
  // Return the current pinned.json object
  try {
    const pinnedPath = path.join(process.cwd(), 'posts', 'pinned.json');
    console.log('Reading pinned.json from:', pinnedPath);
    let pinnedData = { pinned: [], folderEmojis: {} };
    if (fs.existsSync(pinnedPath)) {
      pinnedData = JSON.parse(fs.readFileSync(pinnedPath, 'utf8'));
      console.log('Successfully read pinned.json with data:', pinnedData);
    } else {
      console.log('pinned.json does not exist, using default data');
    }
    return NextResponse.json(pinnedData);
  } catch (error) {
    console.error('Error reading pinned.json:', error);
    return NextResponse.json({ error: 'Error reading pinned.json' }, { status: 500 });
  }
}

export async function PATCH(request: Request) {
  try {
    const body = await request.json();
    const { pinned, folderEmojis } = body; // expects pinned (array) and folderEmojis (object)
    if (!Array.isArray(pinned) || typeof folderEmojis !== 'object') {
      return NextResponse.json({ error: 'Invalid pinned or folderEmojis data' }, { status: 400 });
    }
    const pinnedPath = path.join(process.cwd(), 'posts', 'pinned.json');
    console.log('Saving pinned.json to:', pinnedPath);
    console.log('Saving data:', { pinned, folderEmojis });
    fs.writeFileSync(pinnedPath, JSON.stringify({ pinned, folderEmojis }, null, 2), 'utf8');
    console.log('Successfully saved pinned.json');
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error updating pinned.json:', error);
    return NextResponse.json(
      { error: 'Error updating pinned.json' },
      { status: 500 }
    );
  }
}

export async function PUT(request: Request) {
  try {
    const body = await request.json();
    const { slug, path: folderPath, content } = body;
    if (!slug || typeof content !== 'string') {
      return NextResponse.json({ error: 'Missing slug or content' }, { status: 400 });
    }
    // Compute file path
    const filePath = folderPath && folderPath.trim() !== ''
      ? path.join(postsDirectory, folderPath, `${slug}.md`)
      : path.join(postsDirectory, `${slug}.md`);
    if (!fs.existsSync(filePath)) {
      return NextResponse.json({ error: 'File does not exist' }, { status: 404 });
    }
    fs.writeFileSync(filePath, content, 'utf8');
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error editing post:', error);
    return NextResponse.json({ error: 'Error editing post' }, { status: 500 });
  }
}

export async function DELETE(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const clearLogs = searchParams.get('clearLogs');
    
    if (clearLogs === '1') {
      // Call the Rust backend to clear parser logs
      const rustResult = spawnSync(
        process.cwd() + '/markdown_backend/target/release/markdown_backend',
        ['clear-logs'],
        { encoding: 'utf-8' }
      );
      if (rustResult.status === 0 && rustResult.stdout) {
        return new Response(rustResult.stdout, {
          status: 200,
          headers: { 'Content-Type': 'application/json' },
        });
      } else {
        return new Response(JSON.stringify({ error: rustResult.stderr || rustResult.error }), {
          status: 500,
          headers: { 'Content-Type': 'application/json' },
        });
      }
    }
    
    return NextResponse.json({ error: 'Invalid delete operation' }, { status: 400 });
  } catch (error) {
    console.error('Error clearing logs:', error);
    return NextResponse.json({ error: 'Error clearing logs' }, { status: 500 });
  }
} 