import fs from "node:fs/promises";
import path from "node:path";
import type { ScannerLearningLoadResult, ScannerLearningRepositoryPort, ScannerLearningRules, ScannerLearningSaveResult } from "./contracts.js";

export class ScannerLearningRepository implements ScannerLearningRepositoryPort {
  private readonly filePath: string;

  constructor(userDataPath: string, fileName = "scanner-learning.json") {
    this.filePath = path.join(userDataPath, fileName);
  }

  async load(): Promise<ScannerLearningLoadResult> {
    try {
      const raw = await fs.readFile(this.filePath, "utf8");
      const parsed = JSON.parse(raw) as ScannerLearningRules;
      return {
        ok: true,
        path: this.filePath,
        rules: parsed && typeof parsed === "object" ? parsed : { textReplacements: {} },
      };
    } catch {
      return { ok: true, path: this.filePath, rules: { textReplacements: {} } };
    }
  }

  async save(rules: ScannerLearningRules): Promise<ScannerLearningSaveResult> {
    const current = await this.load();
    const nextTextReplacements = {
      ...((current.rules as { textReplacements?: Record<string, string> })?.textReplacements ?? {}),
      ...((rules as { textReplacements?: Record<string, string> })?.textReplacements ?? {}),
    };
    const payload: ScannerLearningRules = { textReplacements: nextTextReplacements };
    await fs.mkdir(path.dirname(this.filePath), { recursive: true });
    await fs.writeFile(this.filePath, JSON.stringify(payload, null, 2), "utf8");
    return { ok: true, path: this.filePath, rules: payload, total: Object.keys(nextTextReplacements).length };
  }
}
