import { NextResponse } from "next/server";
import fs from "fs";

const MESSAGE_FILE = "/tmp/horus-mc-messages.json";
const TELEGRAM_CHAT_ID = "382315644"; // Haitham's Telegram ID

interface Message {
  id: string;
  role: "user" | "assistant";
  content: string;
  timestamp: number;
  processed: boolean;
}

function getMessages(): Message[] {
  try {
    if (fs.existsSync(MESSAGE_FILE)) {
      return JSON.parse(fs.readFileSync(MESSAGE_FILE, "utf-8"));
    }
  } catch (e) {
    console.error("Error reading messages:", e);
  }
  return [];
}

function saveMessages(messages: Message[]) {
  fs.writeFileSync(MESSAGE_FILE, JSON.stringify(messages, null, 2));
}

async function sendToTelegram(text: string) {
  try {
    const token = process.env.TELEGRAM_BOT_TOKEN;
    if (!token) {
      console.log("No Telegram token, skipping");
      return;
    }
    
    await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        chat_id: TELEGRAM_CHAT_ID,
        text: `💬 MC Chat:\n${text}`,
      }),
    });
  } catch (e) {
    console.error("Telegram error:", e);
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { message, locale = "es" } = body;

    if (!message) {
      return NextResponse.json({ error: "Message required" }, { status: 400 });
    }

    const messages = getMessages();
    
    // Add user message
    const userMessage: Message = {
      id: `msg_${Date.now()}`,
      role: "user",
      content: message,
      timestamp: Date.now(),
      processed: false,
    };
    messages.push(userMessage);
    saveMessages(messages);

    // Forward to Telegram (where Horus is listening)
    await sendToTelegram(message);

    return NextResponse.json({ 
      id: userMessage.id,
      status: "sent",
      message: "Message sent to Horus"
    });

  } catch (error) {
    console.error("Error:", error);
    return NextResponse.json({ error: "Failed" }, { status: 500 });
  }
}

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const lastId = searchParams.get("after");

  const messages = getMessages();
  
  // Get messages after lastId
  let filtered = messages;
  if (lastId) {
    const idx = messages.findIndex(m => m.id === lastId);
    if (idx >= 0) {
      filtered = messages.slice(idx + 1);
    }
  }

  // Return only assistant messages that haven't been fetched
  const response = filtered.filter(m => m.role === "assistant" && !m.processed);

  // Mark as processed
  if (response.length > 0) {
    const processedIds = new Set(response.map(r => r.id));
    const updated = messages.map(m => 
      processedIds.has(m.id) ? { ...m, processed: true } : m
    );
    saveMessages(updated);
  }

  return NextResponse.json({ messages: response });
}
