import { loadConfig } from "./config.js";
import { initLogger, logger } from "./logger.js";
import { TaskLoop } from "./scheduler/task-loop.js";
import { ImprovementLoop } from "./scheduler/improvement-loop.js";
import { startHealthServer, updateHealth } from "./health/server.js";

async function main() {
  console.log(`
╔══════════════════════════════════════╗
║        🤖 Pi Worker v1.0.0          ║
║  Autonomous Asana Task Executor     ║
║  & Project Improvement Agent        ║
╚══════════════════════════════════════╝
`);

  // Load config
  const config = loadConfig();
  initLogger(config.logDir);

  logger.info("main", "Configuration loaded", {
    model: config.piModel,
    pollInterval: `${config.pollIntervalSec}s`,
    improvementInterval: `${config.improvementIntervalSec}s`,
    targetProject: config.targetProjectPath,
    healthPort: config.healthPort,
  });

  // Start health server
  startHealthServer(config.healthPort);
  updateHealth({ status: "ok" });

  // Start task loop (Asana polling)
  const taskLoop = new TaskLoop(config);
  await taskLoop.start();
  updateHealth({ taskLoop: true });

  // Start improvement loop (autonomous project fixes)
  const improvementLoop = new ImprovementLoop(config);
  await improvementLoop.start();
  updateHealth({ improvementLoop: true });

  logger.info("main", "Pi Worker is fully operational 🚀");

  // Graceful shutdown
  const shutdown = () => {
    logger.info("main", "Shutting down...");
    taskLoop.stop();
    improvementLoop.stop();
    updateHealth({ status: "degraded" });
    process.exit(0);
  };

  process.on("SIGINT", shutdown);
  process.on("SIGTERM", shutdown);
}

main().catch((error) => {
  console.error("Fatal error:", error);
  process.exit(1);
});
