import { readFile, writeFile, mkdir } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { homedir } from "node:os";
import yaml from "js-yaml";
import dotenv from "dotenv";
dotenv.config();
// AUTOVIRAL_DATA_DIR relocates ALL on-disk state (works, trends AND config.yaml)
// so tests can run fully isolated. Previously CONFIG_DIR was pinned to homedir
// and ignored the override, so loadConfig/saveConfig always hit the real
// ~/.autoviral/config.yaml — any test that persisted config clobbered the user's
// file. Honour the override here too (production leaves the env var unset, so the
// path is unchanged). Resolved at module load — tests use vi.resetModules.
const CONFIG_DIR = process.env.AUTOVIRAL_DATA_DIR ?? join(homedir(), ".autoviral");
const CONFIG_PATH = join(CONFIG_DIR, "config.yaml");
/** Base data directory for works, trends, etc.
 *  Tests can override via AUTOVIRAL_DATA_DIR; resolved at module load. */
export const dataDir = CONFIG_DIR;
/** Repo root directory — used by the rubric reader and any code that needs
 *  to load files shipped with the package. Resolves to the parent of the
 *  directory containing this module (src/ in dev, dist/ in prod). */
export const repoRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
export function getDefaultConfig() {
    return {
        port: 3271,
        model: "opus",
        // e2e-report F139: minute :07 not :00. Multi-tenant CLI installs all
        // firing on the exact same wall-clock minute look like coordinated
        // scraping to small-red-book / douyin anti-bot heuristics. Offsetting
        // minute (07 chosen arbitrarily but stable, not random — easier debug)
        // breaks the synchronisation without changing the twice-daily cadence.
        research: { enabled: true, schedule: "7 9,21 * * *", platforms: ["douyin", "xiaohongshu"] },
        interests: [],
        analytics: { douyinUrl: "", collectInterval: 60, enabled: true },
    };
}
export async function ensureDir(dirPath) {
    await mkdir(dirPath, { recursive: true });
}
export async function loadConfig() {
    await ensureDir(CONFIG_DIR);
    try {
        const raw = await readFile(CONFIG_PATH, "utf-8");
        const parsed = yaml.load(raw);
        const config = { ...getDefaultConfig(), ...parsed };
        config.interests = config.interests ?? [];
        // .env overrides
        if (process.env.OPENROUTER_API_KEY) {
            config.openrouter = { apiKey: process.env.OPENROUTER_API_KEY };
        }
        if (process.env.EVERMEMOS_API_KEY) {
            if (!config.memory) {
                config.memory = { apiKey: "", userId: "autoviral-user", syncEnabled: false };
            }
            config.memory.apiKey = process.env.EVERMEMOS_API_KEY;
        }
        return config;
    }
    catch {
        const config = getDefaultConfig();
        await saveConfig(config);
        return config;
    }
}
export async function saveConfig(config) {
    await ensureDir(CONFIG_DIR);
    const raw = yaml.dump(config, { lineWidth: -1 });
    await writeFile(CONFIG_PATH, raw, "utf-8");
}
export function getConfigDir() {
    return CONFIG_DIR;
}
//# sourceMappingURL=config.js.map