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

const STORAGE_FILE = path.join(process.cwd(), "data", "eod_briefs.json");

const DISCORD_BOT_TOKEN = process.env.DISCORD_BOT_TOKEN || "MTQ3MTk4OTUzNjE1MzQwMzU5Nw.Ghtj4n.g-tl-Ijhfn9cg6zUCUIVd94EdwL32KmlVgRoSc";
const EOD_CHANNEL = "1476344633406656785";

function ensureStorage() {
  const dir = path.dirname(STORAGE_FILE);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
  if (!fs.existsSync(STORAGE_FILE)) {
    fs.writeFileSync(STORAGE_FILE, "[]");
  }
}

function getBriefs() {
  ensureStorage();
  return JSON.parse(fs.readFileSync(STORAGE_FILE, "utf-8"));
}

function saveBriefs(data: any[]) {
  ensureStorage();
  fs.writeFileSync(STORAGE_FILE, JSON.stringify(data, null, 2));
}

function formatEODBrief(data: any): string {
  return `🌙 END OF DAY - ${data.date || new Date().toISOString().split('T')[0]}

✅ COMPLETED TODAY
${(data.completed || []).map((c: string) => `- ${c}`).join('\n')}

📊 PROGRESS
${Object.entries(data.progress || {}).map(([k, v]) => `${k}: ${v}`).join('\n')}

🧠 COUNCIL
${Object.entries(data.council || {}).map(([k, v]) => `- ${k}: ${v}`).join('\n')}

🎯 TOMORROW
${(data.tomorrow || []).map((t: string) => `- ${t}`).join('\n')}`;
}

export async function GET() {
  const briefs = getBriefs();
  return NextResponse.json(briefs);
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    const brief = {
      id: `eod-${Date.now()}`,
      date: body.date || new Date().toISOString().split('T')[0],
      completed: body.completed || [],
      progress: body.progress || {},
      council: body.council || {},
      tomorrow: body.tomorrow || [],
      created_at: new Date().toISOString()
    };
    
    const briefs = getBriefs();
    briefs.unshift(brief);
    saveBriefs(briefs);
    
    // Send to Discord
    const discordMessage = formatEODBrief(body);
    await fetch(`https://discord.com/api/v10/channels/${EOD_CHANNEL}/messages`, {
      method: "POST",
      headers: {
        "Authorization": `Bot ${DISCORD_BOT_TOKEN}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ content: discordMessage }),
    });
    
    return NextResponse.json({ success: true, brief });
  } catch (error) {
    console.error("EOD brief error:", error);
    return NextResponse.json({ error: "Failed to save brief" }, { status: 500 });
  }
}
