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

const STORAGE_DIR = path.join(process.cwd(), "data");
const TEMPLATES_FILE = path.join(STORAGE_DIR, "recurring-templates.json");
const LOGS_FILE = path.join(STORAGE_DIR, "execution-logs.json");
const CHANGELOG_FILE = path.join(STORAGE_DIR, "changelog.json");
const OUTPUTS_FILE = path.join(STORAGE_DIR, "agent-outputs.json");

function ensureDir() {
  if (!fs.existsSync(STORAGE_DIR)) {
    fs.mkdirSync(STORAGE_DIR, { recursive: true });
  }
}

function readJSON(file: string, defaultValue: any = []) {
  ensureDir();
  if (!fs.existsSync(file)) {
    fs.writeFileSync(file, JSON.stringify(defaultValue));
    return defaultValue;
  }
  try {
    return JSON.parse(fs.readFileSync(file, "utf-8"));
  } catch {
    return defaultValue;
  }
}

function writeJSON(file: string, data: any) {
  ensureDir();
  fs.writeFileSync(file, JSON.stringify(data, null, 2));
}

// Templates CRUD
export async function GET() {
  const templates = readJSON(TEMPLATES_FILE, []);
  return NextResponse.json(templates);
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, template, templateId, enabled } = body;
    
    const templates = readJSON(TEMPLATES_FILE, []);
    
    if (action === "toggle") {
      const idx = templates.findIndex((t: any) => t.id === templateId);
      if (idx >= 0) {
        templates[idx].enabled = enabled;
        writeJSON(TEMPLATES_FILE, templates);
        return NextResponse.json({ success: true, templates });
      }
    }
    
    if (action === "save") {
      const idx = templates.findIndex((t: any) => t.id === template.id);
      if (idx >= 0) {
        templates[idx] = { ...templates[idx], ...template };
      } else {
        templates.push({ ...template, runCount: 0, enabled: false });
      }
      writeJSON(TEMPLATES_FILE, templates);
      return NextResponse.json({ success: true, templates });
    }
    
    if (action === "delete") {
      const filtered = templates.filter((t: any) => t.id !== templateId);
      writeJSON(TEMPLATES_FILE, filtered);
      return NextResponse.json({ success: true, templates: filtered });
    }
    
    if (action === "run-now") {
      // Trigger immediate execution
      const idx = templates.findIndex((t: any) => t.id === templateId);
      if (idx >= 0) {
        const template = templates[idx];
        
        // Create execution log
        const logs = readJSON(LOGS_FILE, []);
        const logId = `log-${Date.now()}`;
        const newLog = {
          id: logId,
          templateId: template.id,
          agent: template.agent,
          taskTitle: template.taskTemplate.title,
          startedAt: new Date().toISOString(),
          status: "running",
          output: "Agent executing..."
        };
        logs.unshift(newLog);
        writeJSON(LOGS_FILE, logs);
        
        // Update template
        templates[idx].lastRun = new Date().toISOString();
        templates[idx].runCount = (templates[idx].runCount || 0) + 1;
        writeJSON(TEMPLATES_FILE, templates);
        
        // TODO: Actually dispatch to OpenClaw agent here
        // For now, simulate completion after delay
        
        return NextResponse.json({ 
          success: true, 
          templates,
          executionLog: newLog
        });
      }
    }
    
    return NextResponse.json({ error: "Invalid action" }, { status: 400 });
    
  } catch (error) {
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
