/**
 * Phase 1 — CliWriter
 * All CLI output goes through here. No direct console.log/chalk anywhere else.
 * Wraps the existing OMK theme/style system for backward compatibility.
 */
import { appendFileSync } from "node:fs";
import { style, status } from "../../theme/index.js";
const STATUS_ICON = {
    running: "▶",
    pending: "◯",
    completed: "✓",
    failed: "✕",
};
function writeLine(stream, text) {
    stream.write(text + "\n");
}
function writeFileLine(path, text) {
    try {
        appendFileSync(path, text + "\n", "utf-8");
    }
    catch {
        // silently drop file-write failures; stdout remains the fallback
    }
}
export function createCliWriter(profile) {
    const isFile = profile.destination === "file" && profile.outputFile;
    const filePath = profile.outputFile;
    const out = (text) => {
        if (isFile && filePath) {
            writeFileLine(filePath, text);
        }
        else {
            writeLine(process.stdout, text);
        }
    };
    const err = (text) => {
        if (isFile && filePath) {
            writeFileLine(filePath, text);
        }
        else {
            writeLine(process.stderr, text);
        }
    };
    const raw = (stream, content) => {
        if (isFile && filePath) {
            try {
                appendFileSync(filePath, content, "utf-8");
            }
            catch {
                /* ignore */
            }
        }
        else {
            stream.write(content);
        }
    };
    return {
        info(message) {
            out(style.blue("ℹ ") + message);
        },
        success(message) {
            out(status.success(message));
        },
        warning(message) {
            err(status.warn(message));
        },
        error(message) {
            err(status.fail(message));
        },
        agent(agentName, message) {
            out(style.purple("● ") + style.bold + agentName + style.reset + ": " + message);
        },
        task(taskTitle, taskStatus) {
            const icon = STATUS_ICON[taskStatus] ?? "?";
            out(style.cyan(icon + " ") + taskTitle + " " + style.gray(`[${taskStatus}]`));
        },
        trace(message) {
            out(style.dim + message + style.reset);
        },
        rawStdout(content) {
            raw(process.stdout, content);
        },
        rawStderr(content) {
            raw(process.stderr, content);
        },
    };
}
