import { join } from "node:path";
import { existsSync, readdirSync, statSync, rmSync } from "node:fs";
import { Cron } from "croner";
import type { Logger } from "pino";

const HU_BOT_DIR = ".hu-bot";
const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;

export class PromptCleanupScheduler {
  private job: Cron | null = null;

  constructor(
    private readonly workdirPath: string,
    private readonly logger: Logger,
  ) {}

  start(): void {
    if (this.job) return;

    // Every Sunday at 03:00 UTC
    this.job = new Cron("0 3 * * 0", { protect: true }, () => {
      this.cleanup();
    });

    this.logger.info("prompt_cleanup_scheduler_started");
  }

  stop(): void {
    this.job?.stop();
    this.job = null;
  }

  cleanup(): void {
    const huBotDir = join(this.workdirPath, HU_BOT_DIR);
    if (!existsSync(huBotDir)) return;

    const now = Date.now();
    let removed = 0;

    for (const entry of readdirSync(huBotDir, { withFileTypes: true })) {
      if (!entry.isDirectory()) continue;

      const dirPath = join(huBotDir, entry.name);
      try {
        const age = now - statSync(dirPath).mtimeMs;
        if (age > MAX_AGE_MS) {
          rmSync(dirPath, { recursive: true, force: true });
          removed++;
        }
      } catch {
        /* skip entries that vanish mid-iteration */
      }
    }

    if (removed > 0) {
      this.logger.info({ removed }, "prompt_cleanup_completed");
    }
  }
}
