#!/usr/bin/env node
/**
 * GooseFactory Learning Pipeline Service
 *
 * Standalone service that processes feedback events through the learning pipeline.
 * Can run as:
 * - HTTP server accepting feedback submissions
 * - CLI for testing and manual processing
 */

import * as http from "node:http";
import { processFeedback, runFullAnalysis } from "./pipeline/index.js";
import type { FeedbackEvent } from "./types.js";

const PORT = process.env.LEARNING_PORT ? parseInt(process.env.LEARNING_PORT) : 4001;
const DATA_DIR = process.env.FEEDBACK_DATA_DIR || `${process.env.HOME}/.config/goose/factory`;

console.log("╔═══════════════════════════════════════════════════════════════");
console.log("║ GooseFactory Learning Pipeline Service");
console.log("╠═══════════════════════════════════════════════════════════════");
console.log(`║ Port:     ${PORT}`);
console.log(`║ Data Dir: ${DATA_DIR}`);
console.log("╚═══════════════════════════════════════════════════════════════\n");

/**
 * Simple HTTP server for feedback processing
 */
const server = http.createServer(async (req, res) => {
  // CORS headers
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type");

  if (req.method === "OPTIONS") {
    res.writeHead(204);
    res.end();
    return;
  }

  // Health check
  if (req.url === "/health" && req.method === "GET") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ 
      status: "ok", 
      service: "learning-pipeline",
      dataDir: DATA_DIR 
    }));
    return;
  }

  // Process feedback: POST /feedback
  if (req.url === "/feedback" && req.method === "POST") {
    let body = "";
    req.on("data", (chunk) => {
      body += chunk.toString();
    });

    req.on("end", async () => {
      try {
        const feedbackData = JSON.parse(body);
        console.log(`\n[${new Date().toISOString()}] Processing feedback event...`);
        
        const result = await processFeedback(feedbackData, {
          dataDir: DATA_DIR,
          memoryDir: `${DATA_DIR}/memory`,
          analyzeOnEvery: false,
          analysisThreshold: 10,
        });

        if (result.success) {
          console.log(`✓ Feedback processed successfully (ID: ${result.eventId})`);
          console.log(`  Processing time: ${result.processingTimeMs}ms`);
          
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({
            success: true,
            eventId: result.eventId,
            processingTimeMs: result.processingTimeMs,
          }));
        } else {
          console.error(`✗ Feedback processing failed: ${result.error}`);
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({
            success: false,
            error: result.error,
          }));
        }
      } catch (error) {
        console.error("✗ Error processing feedback:", error);
        res.writeHead(500, { "Content-Type": "application/json" });
        res.end(JSON.stringify({
          success: false,
          error: error instanceof Error ? error.message : String(error),
        }));
      }
    });
    return;
  }

  // Run full analysis: POST /analyze
  if (req.url === "/analyze" && req.method === "POST") {
    try {
      console.log(`\n[${new Date().toISOString()}] Running full analysis...`);
      
      const result = await runFullAnalysis({
        dataDir: DATA_DIR,
        memoryDir: `${DATA_DIR}/memory`,
      });

      if (result.success) {
        console.log(`✓ Analysis completed successfully`);
        console.log(`  Processing time: ${result.processingTimeMs}ms`);
        
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify({
          success: true,
          processingTimeMs: result.processingTimeMs,
        }));
      } else {
        console.error(`✗ Analysis failed: ${result.error}`);
        res.writeHead(500, { "Content-Type": "application/json" });
        res.end(JSON.stringify({
          success: false,
          error: result.error,
        }));
      }
    } catch (error) {
      console.error("✗ Error running analysis:", error);
      res.writeHead(500, { "Content-Type": "application/json" });
      res.end(JSON.stringify({
        success: false,
        error: error instanceof Error ? error.message : String(error),
      }));
    }
    return;
  }

  // Not found
  res.writeHead(404, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ error: "Not found" }));
});

server.listen(PORT, () => {
  console.log(`✓ Learning Pipeline service listening on port ${PORT}\n`);
  console.log("Endpoints:");
  console.log("  GET  /health   - Health check");
  console.log("  POST /feedback - Submit feedback for processing");
  console.log("  POST /analyze  - Run full analysis on stored data\n");
});

// Graceful shutdown
process.on("SIGTERM", () => {
  console.log("\n\nShutting down gracefully...");
  server.close(() => {
    console.log("✓ Server closed");
    process.exit(0);
  });
});

process.on("SIGINT", () => {
  console.log("\n\nShutting down gracefully...");
  server.close(() => {
    console.log("✓ Server closed");
    process.exit(0);
  });
});
