"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CONFIG_PATH = void 0;
exports.loadConfig = loadConfig;
exports.saveConfig = saveConfig;
exports.resolveProfile = resolveProfile;
exports.resolveInitialDebug = resolveInitialDebug;
exports.resolveInitialConfirmTransactions = resolveInitialConfirmTransactions;
exports.profileToMetadata = profileToMetadata;
const promises_1 = __importDefault(require("node:fs/promises"));
const node_os_1 = __importDefault(require("node:os"));
const node_path_1 = __importDefault(require("node:path"));
const terminal_1 = require("./terminal");
const CONFIG_DIR = node_path_1.default.join(node_os_1.default.homedir(), ".dzapai");
exports.CONFIG_PATH = node_path_1.default.join(CONFIG_DIR, "config.json");
function isWalletProfile(value) {
    if (!value || typeof value !== "object" || Array.isArray(value)) {
        return false;
    }
    const candidate = value;
    return (typeof candidate.wallet === "string" &&
        candidate.wallet.trim().length > 0 &&
        typeof candidate.chain === "string" &&
        candidate.chain.trim().length > 0 &&
        typeof candidate.blockchain === "string" &&
        candidate.blockchain.trim().length > 0 &&
        (candidate.privateKey === undefined ||
            (typeof candidate.privateKey === "string")));
}
async function loadConfig() {
    try {
        const raw = await promises_1.default.readFile(exports.CONFIG_PATH, "utf-8");
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
            return {};
        }
        const config = parsed;
        const resolved = {};
        if (isWalletProfile(config.profile)) {
            resolved.profile = {
                wallet: config.profile.wallet,
                chain: config.profile.chain,
                blockchain: config.profile.blockchain,
                privateKey: typeof config.profile.privateKey === "string" ? config.profile.privateKey : "",
            };
        }
        if (typeof config.debug === "boolean") {
            resolved.debug = config.debug;
        }
        if (typeof config.confirmTransactions === "boolean") {
            resolved.confirmTransactions = config.confirmTransactions;
        }
        return resolved;
    }
    catch (_a) {
        return {};
    }
}
async function saveConfig(config) {
    await promises_1.default.mkdir(CONFIG_DIR, { recursive: true });
    await promises_1.default.writeFile(exports.CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
}
async function askYesNo(rl, question, defaultYes) {
    const suffix = defaultYes ? "[Y/n]" : "[y/N]";
    while (true) {
        const answer = (await rl.question((0, terminal_1.colorize)(`${question} ${suffix} `, terminal_1.ansi.cyan))).trim().toLowerCase();
        if (answer.length === 0) {
            return defaultYes;
        }
        if (answer === "y" || answer === "yes") {
            return true;
        }
        if (answer === "n" || answer === "no") {
            return false;
        }
        (0, terminal_1.logLine)("warn", "Please answer with y or n.");
    }
}
async function askRequired(rl, question, defaultValue = "") {
    while (true) {
        const suffix = defaultValue ? ` (${defaultValue})` : "";
        const answer = (await rl.question((0, terminal_1.colorize)(`${question}${suffix}: `, terminal_1.ansi.cyan))).trim();
        const resolved = answer.length > 0 ? answer : defaultValue;
        if (resolved.length > 0) {
            return resolved;
        }
        (0, terminal_1.logLine)("warn", `${question} is required.`);
    }
}
async function resolveProfile(rl, config) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    if (config.profile) {
        const useSaved = await askYesNo(rl, "Use this profile?", true);
        if (useSaved) {
            if (config.profile.privateKey.trim().length > 0) {
                return config.profile;
            }
            (0, terminal_1.logLine)("warn", "Saved profile is missing a private key. Please provide it to continue.");
        }
    }
    const wallet = await askRequired(rl, "Wallet", (_b = (_a = config.profile) === null || _a === void 0 ? void 0 : _a.wallet) !== null && _b !== void 0 ? _b : "");
    const chain = await askRequired(rl, "Chain", (_d = (_c = config.profile) === null || _c === void 0 ? void 0 : _c.chain) !== null && _d !== void 0 ? _d : "");
    const blockchain = await askRequired(rl, "Blockchain", (_f = (_e = config.profile) === null || _e === void 0 ? void 0 : _e.blockchain) !== null && _f !== void 0 ? _f : "evm");
    (0, terminal_1.logLine)("warn", "Security notice: Your private key stays local in this CLI and is never sent to any LLM or DZap server.");
    const privateKey = await askRequired(rl, "Wallet Private Key", (_h = (_g = config.profile) === null || _g === void 0 ? void 0 : _g.privateKey) !== null && _h !== void 0 ? _h : "");
    const profile = { wallet, chain, blockchain, privateKey };
    config.profile = profile;
    await saveConfig(config);
    return profile;
}
function parseBooleanFlag(raw) {
    if (!raw) {
        return false;
    }
    const normalized = raw.trim().toLowerCase();
    return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
}
function resolveInitialDebug(config) {
    if (typeof config.debug === "boolean") {
        return config.debug;
    }
    return parseBooleanFlag(process.env.DZAP_CLI_DEBUG);
}
function resolveInitialConfirmTransactions(config) {
    if (typeof config.confirmTransactions === "boolean") {
        return config.confirmTransactions;
    }
    if (process.env.DZAP_CONFIRM_TRANSACTIONS !== undefined) {
        return parseBooleanFlag(process.env.DZAP_CONFIRM_TRANSACTIONS);
    }
    return true;
}
function profileToMetadata(profile) {
    return {
        accountInfo: [
            {
                blockchain: profile.blockchain,
                chain: profile.chain,
                user_account: profile.wallet,
                private_key: profile.privateKey,
            },
        ],
    };
}
