import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const PROJECT_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
export const PIBO_LIBRARY_BASE_PROMPT_PATH = resolve(PROJECT_ROOT, "context/pibo-system-prompt.md");
function getBasePromptStatePath(cwd) {
    return resolve(cwd, ".pibo/base-prompt.json");
}
function getCustomBasePromptPath(cwd) {
    return resolve(cwd, ".pibo/base-prompt.md");
}
function normalizeMode(value) {
    return value === "custom" ? "custom" : "library";
}
function readBasePromptState(cwd) {
    const path = getBasePromptStatePath(cwd);
    if (!existsSync(path))
        return { mode: "library" };
    try {
        const parsed = JSON.parse(readFileSync(path, "utf-8"));
        return {
            mode: normalizeMode(parsed.mode),
            updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : undefined,
        };
    }
    catch {
        return { mode: "library" };
    }
}
function writeBasePromptState(cwd, state) {
    const path = getBasePromptStatePath(cwd);
    mkdirSync(dirname(path), { recursive: true });
    writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`);
}
export function getActivePiboBasePromptPath(cwd = process.cwd()) {
    const legacyOverridePath = resolve(cwd, ".pibo/SYSTEM.md");
    if (existsSync(legacyOverridePath))
        return undefined;
    const customPath = getCustomBasePromptPath(cwd);
    const state = readBasePromptState(cwd);
    if (state.mode === "custom" && existsSync(customPath))
        return customPath;
    return existsSync(PIBO_LIBRARY_BASE_PROMPT_PATH) ? PIBO_LIBRARY_BASE_PROMPT_PATH : undefined;
}
export async function readPiboBasePrompt(cwd = process.cwd()) {
    const state = readBasePromptState(cwd);
    const customPath = getCustomBasePromptPath(cwd);
    const customExists = existsSync(customPath);
    const [libraryMarkdown, customMarkdown] = await Promise.all([
        readFile(PIBO_LIBRARY_BASE_PROMPT_PATH, "utf-8"),
        customExists ? readFile(customPath, "utf-8") : Promise.resolve(""),
    ]);
    return {
        mode: state.mode,
        effectiveMode: state.mode === "custom" && customExists ? "custom" : "library",
        library: {
            path: PIBO_LIBRARY_BASE_PROMPT_PATH,
            markdown: libraryMarkdown,
        },
        custom: {
            path: customPath,
            markdown: customMarkdown,
            exists: customExists,
            updatedAt: customExists ? state.updatedAt : undefined,
        },
    };
}
export async function savePiboCustomBasePrompt(markdown, cwd = process.cwd()) {
    const path = getCustomBasePromptPath(cwd);
    mkdirSync(dirname(path), { recursive: true });
    const updatedAt = new Date().toISOString();
    await writeFile(path, markdown);
    writeBasePromptState(cwd, { mode: "custom", updatedAt });
    return readPiboBasePrompt(cwd);
}
export function setPiboBasePromptMode(mode, cwd = process.cwd()) {
    const existing = readBasePromptState(cwd);
    const customPath = getCustomBasePromptPath(cwd);
    if (mode === "custom" && !existsSync(customPath)) {
        mkdirSync(dirname(customPath), { recursive: true });
        writeFileSync(customPath, readFileSync(PIBO_LIBRARY_BASE_PROMPT_PATH, "utf-8"));
    }
    writeBasePromptState(cwd, {
        mode,
        updatedAt: mode === "custom" ? existing.updatedAt ?? new Date().toISOString() : existing.updatedAt,
    });
    const state = readBasePromptState(cwd);
    const customExists = existsSync(customPath);
    return {
        mode: state.mode,
        effectiveMode: state.mode === "custom" && customExists ? "custom" : "library",
        library: {
            path: PIBO_LIBRARY_BASE_PROMPT_PATH,
            markdown: readFileSync(PIBO_LIBRARY_BASE_PROMPT_PATH, "utf-8"),
        },
        custom: {
            path: customPath,
            markdown: customExists ? readFileSync(customPath, "utf-8") : "",
            exists: customExists,
            updatedAt: customExists ? state.updatedAt : undefined,
        },
    };
}
