/**
 * Issues configuration persistence and resolution.
 *
 * Stored under the user's Neotoma config at `~/.config/neotoma/config.json`
 * as `issues.*`. Environment variables take precedence over stored config.
 */
import { promises as fs } from "node:fs";
import path from "node:path";
import os from "node:os";
import { DEFAULT_ISSUES_CONFIG, DEFAULT_ISSUES_TARGET_URL } from "./types.js";
function configFilePath() {
    const home = process.env.HOME || process.env.USERPROFILE || os.homedir();
    return path.join(home, ".config", "neotoma", "config.json");
}
async function readConfig() {
    try {
        const raw = await fs.readFile(configFilePath(), "utf8");
        return JSON.parse(raw);
    }
    catch (err) {
        if (err.code === "ENOENT")
            return {};
        throw err;
    }
}
async function writeConfig(cfg) {
    const p = configFilePath();
    await fs.mkdir(path.dirname(p), { recursive: true });
    await fs.writeFile(p, JSON.stringify(cfg, null, 2), "utf8");
}
/**
 * Load the resolved issues config, with env var overrides applied.
 */
export async function loadIssuesConfig() {
    const cfg = await readConfig();
    const stored = cfg.issues ?? {};
    const githubAuth = process.env.NEOTOMA_ISSUES_GITHUB_TOKEN
        ? "token"
        : (stored.github_auth ?? DEFAULT_ISSUES_CONFIG.github_auth);
    const repo = process.env.NEOTOMA_ISSUES_REPO ?? stored.repo ?? DEFAULT_ISSUES_CONFIG.repo;
    const reportingMode = process.env.NEOTOMA_ISSUES_REPORTING_MODE ??
        stored.reporting_mode ??
        DEFAULT_ISSUES_CONFIG.reporting_mode;
    const syncStalenessMs = process.env.NEOTOMA_ISSUES_SYNC_STALENESS_MS
        ? parseInt(process.env.NEOTOMA_ISSUES_SYNC_STALENESS_MS, 10)
        : (stored.sync_staleness_ms ?? DEFAULT_ISSUES_CONFIG.sync_staleness_ms);
    // When the env var is **absent**, fall back to stored config then the product
    // default operator URL. When it is **present** (including empty string), honor
    // it so isolated tests and operators can disable remote forwarding without
    // inheriting DEFAULT_ISSUES_TARGET_URL from this merge order.
    const rawIssuesTargetEnv = process.env.NEOTOMA_ISSUES_TARGET_URL;
    const hasIssuesTargetEnv = rawIssuesTargetEnv !== undefined;
    const envTargetTrimmed = typeof rawIssuesTargetEnv === "string" ? rawIssuesTargetEnv.trim() : rawIssuesTargetEnv;
    const envTarget = hasIssuesTargetEnv
        ? typeof envTargetTrimmed === "string" && envTargetTrimmed.length > 0
            ? envTargetTrimmed
            : ""
        : undefined;
    const storedRaw = typeof stored.target_url === "string" ? stored.target_url.trim() : stored.target_url;
    const storedTarget = typeof storedRaw === "string" && storedRaw.length > 0 ? storedRaw : undefined;
    const targetUrl = envTarget !== undefined ? envTarget : (storedTarget ?? DEFAULT_ISSUES_TARGET_URL);
    const envAuthorAliasRaw = process.env.NEOTOMA_ISSUES_AUTHOR_ALIAS?.trim();
    const envAuthorAlias = envAuthorAliasRaw && envAuthorAliasRaw.length > 0 ? envAuthorAliasRaw : undefined;
    const storedAuthorAliasRaw = typeof stored.author_alias === "string" ? stored.author_alias.trim() : stored.author_alias;
    const storedAuthorAlias = typeof storedAuthorAliasRaw === "string" && storedAuthorAliasRaw.length > 0
        ? storedAuthorAliasRaw
        : null;
    return {
        github_auth: githubAuth,
        repo,
        reporting_mode: reportingMode,
        sync_staleness_ms: syncStalenessMs,
        configured_at: stored.configured_at ?? null,
        target_url: targetUrl,
        author_alias: envAuthorAlias ?? storedAuthorAlias,
    };
}
/**
 * Persist partial updates to the issues config section.
 */
export async function updateIssuesConfig(updates) {
    const cfg = await readConfig();
    const current = cfg.issues ?? {};
    const merged = {
        ...DEFAULT_ISSUES_CONFIG,
        ...current,
        ...updates,
        configured_at: new Date().toISOString(),
    };
    cfg.issues = merged;
    await writeConfig(cfg);
    return merged;
}
/**
 * Check if issues have been configured (user has gone through first-time setup).
 */
export async function isIssuesConfigured() {
    const cfg = await loadIssuesConfig();
    return cfg.configured_at !== null;
}
//# sourceMappingURL=config.js.map