import { app } from "electron";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import type { AppConfig, ConfigPatch } from "../../packages/shared/src";

const DEFAULT_CONFIG: AppConfig = {
  saveFolder: null,
  primarySaveFile: null,
  activeDynastyId: null
};

export function getConfigPath(): string {
  return join(app.getPath("userData"), "config.json");
}

export function readConfig(): AppConfig {
  const configPath = getConfigPath();
  if (!existsSync(configPath)) return { ...DEFAULT_CONFIG };

  try {
    const parsed = JSON.parse(readFileSync(configPath, "utf-8")) as ConfigPatch;
    return normalizeConfig(parsed);
  } catch {
    return { ...DEFAULT_CONFIG };
  }
}

export function writeConfig(patch: ConfigPatch): AppConfig {
  const current = readConfig();
  const next = normalizeConfig({ ...current, ...patch });
  const configPath = getConfigPath();
  mkdirSync(dirname(configPath), { recursive: true });
  writeFileSync(configPath, `${JSON.stringify(next, null, 2)}\n`, "utf-8");
  return next;
}

function normalizeConfig(value: ConfigPatch): AppConfig {
  return {
    saveFolder: normalizeString(value.saveFolder),
    primarySaveFile: normalizeString(value.primarySaveFile),
    activeDynastyId: normalizeString(value.activeDynastyId)
  };
}

function normalizeString(value: unknown): string | null {
  return typeof value === "string" && value.trim().length > 0
    ? value.trim()
    : null;
}
