import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
// ---------------------------------------------------------------------------
// Replicate API token management
//
// Two-tier lookup: REPLICATE_API_TOKEN env var first, then ~/.replicate/api-token
// file. Token format: r8_ prefix.
// ---------------------------------------------------------------------------
const TOKEN_DIR = join(homedir(), ".replicate");
const TOKEN_FILE = join(TOKEN_DIR, "api-token");
const TOKEN_PREFIX = "r8_";
export function readToken() {
    // Env var takes precedence
    const envToken = process.env.REPLICATE_API_TOKEN;
    if (envToken) {
        console.error(`[replicate-key] read source=env`);
        return { token: envToken, source: "env" };
    }
    // Fall back to file
    try {
        if (existsSync(TOKEN_FILE)) {
            const token = readFileSync(TOKEN_FILE, "utf-8").trim();
            if (token) {
                console.error(`[replicate-key] read source=file`);
                return { token, source: "file" };
            }
        }
    }
    catch {
        // File read error — treat as missing
    }
    console.error(`[replicate-key] read source=none`);
    return null;
}
export function writeToken(token) {
    if (!token.startsWith(TOKEN_PREFIX)) {
        throw new Error(`Invalid token format — must start with "${TOKEN_PREFIX}"`);
    }
    mkdirSync(TOKEN_DIR, { recursive: true });
    writeFileSync(TOKEN_FILE, token, { mode: 0o600 });
    console.error(`[replicate-key] write path=${TOKEN_FILE}`);
}
export function hasToken() {
    return readToken() !== null;
}
export async function validateToken(token) {
    const start = Date.now();
    try {
        const res = await fetch("https://api.replicate.com/v1/account", {
            headers: { Authorization: `Bearer ${token}` },
        });
        const latencyMs = Date.now() - start;
        if (res.ok) {
            console.error(`[replicate-key] validate status=valid latency=${latencyMs}ms`);
            return { status: "valid", latencyMs };
        }
        if (res.status === 401 || res.status === 403) {
            console.error(`[replicate-key] validate status=auth_error latency=${latencyMs}ms`);
            return { status: "auth_error", latencyMs };
        }
        const body = await res.text().catch(() => "");
        console.error(`[replicate-key] validate status=error latency=${latencyMs}ms`);
        return { status: "error", latencyMs, error: `HTTP ${res.status}: ${body.slice(0, 200)}` };
    }
    catch (err) {
        const latencyMs = Date.now() - start;
        const msg = err instanceof Error ? err.message : String(err);
        console.error(`[replicate-key] validate status=error latency=${latencyMs}ms`);
        return { status: "error", latencyMs, error: msg };
    }
}
//# sourceMappingURL=replicate-key.js.map