import { join } from "node:path";

import { config } from "../config.js";
import {
  atomicWriteJson,
  ensureDirectory,
  readJsonFile,
} from "../utils/fileStore.js";

export type SessionLearningState = {
  lastGatedTurn: number;
  lastReviewedTurn: number;
  sessionId: string;
  updatedAt: string;
};

export class SessionLearningStateStore {
  constructor(private readonly baseDir = config.SESSION_LEARNING_STATE_STORAGE_DIR) {}

  async initialize() {
    await ensureDirectory(this.baseDir);
  }

  async read(sessionId: string): Promise<SessionLearningState> {
    const existing = await readJsonFile<SessionLearningState>(this.filePath(sessionId));
    if (existing) {
      return {
        lastGatedTurn: existing.lastGatedTurn,
        lastReviewedTurn: existing.lastReviewedTurn,
        sessionId: existing.sessionId,
        updatedAt: existing.updatedAt,
      };
    }
    return {
      lastGatedTurn: 0,
      lastReviewedTurn: 0,
      sessionId,
      updatedAt: new Date(0).toISOString(),
    };
  }

  async write(state: SessionLearningState) {
    await atomicWriteJson(this.filePath(state.sessionId), {
      ...state,
      updatedAt: new Date().toISOString(),
    });
  }

  async completeReview(sessionId: string, reviewedTurnCount: number) {
    const current = await this.read(sessionId);
    await this.write({
      ...current,
      lastGatedTurn: Math.max(current.lastGatedTurn, reviewedTurnCount),
      lastReviewedTurn: reviewedTurnCount,
    });
  }

  async completeGate(sessionId: string, gatedTurnCount: number) {
    const current = await this.read(sessionId);
    await this.write({
      ...current,
      lastGatedTurn: gatedTurnCount,
    });
  }

  private filePath(sessionId: string) {
    return join(this.baseDir, `${sessionId}.json`);
  }
}
