"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.C = exports.CELL_DIR = exports.DAEMON_URL = void 0;
exports.getProjectName = getProjectName;
exports.parseArgs = parseArgs;
exports.getArg = getArg;
exports.httpGet = httpGet;
exports.httpPost = httpPost;
exports.isPidAlive = isPidAlive;
exports.isDaemonRunning = isDaemonRunning;
exports.ensureDir = ensureDir;
exports.readJsonSafe = readJsonSafe;
exports.printHeader = printHeader;
exports.printSuccess = printSuccess;
exports.printWarning = printWarning;
exports.printDim = printDim;
exports.withError = withError;
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const chalk_1 = __importDefault(require("chalk"));
// ─── Constants ──────────────────────────────────────────────────────────────
exports.DAEMON_URL = 'http://localhost:9876';
exports.CELL_DIR = path.join(os.homedir(), '.fivo', 'cell');
// ─── Color Helpers ──────────────────────────────────────────────────────────
exports.C = {
    primary: chalk_1.default.hex('#FFAB40'),
    success: chalk_1.default.green,
    warn: chalk_1.default.yellow,
    dim: chalk_1.default.dim,
    bold: chalk_1.default.bold,
    num: (s) => chalk_1.default.hex('#FFAB40').bold(s),
};
// ─── Project Detection ──────────────────────────────────────────────────────
function getProjectName() {
    return path.basename(process.cwd());
}
// ─── Argument Parsing ───────────────────────────────────────────────────────
function parseArgs(argv) {
    const out = [];
    let buf = '';
    let inQuote = false;
    for (const a of argv) {
        if (inQuote) {
            buf += ' ' + a;
            if (a.endsWith('"')) {
                out.push(buf.slice(0, -1));
                buf = '';
                inQuote = false;
            }
        }
        else if (a.startsWith('"') && !a.endsWith('"')) {
            buf = a.slice(1);
            inQuote = true;
        }
        else if (a.startsWith('"') && a.endsWith('"') && a.length > 1) {
            out.push(a.slice(1, -1));
        }
        else {
            out.push(a);
        }
    }
    if (buf)
        out.push(buf);
    return out;
}
function getArg(args, name) {
    const idx = args.indexOf(name);
    if (idx === -1)
        return null;
    return args[idx + 1] || null;
}
// ─── HTTP Helpers ───────────────────────────────────────────────────────────
function httpGet(path) {
    return new Promise((resolve, reject) => {
        const http = require('http');
        const req = http.request(`${exports.DAEMON_URL}${path}`, { method: 'GET', timeout: 5000 }, (res) => {
            let data = '';
            res.on('data', (chunk) => { data += chunk ? chunk.toString() : ''; });
            res.on('end', () => {
                try {
                    resolve(JSON.parse(data));
                }
                catch {
                    resolve(data);
                }
            });
        });
        req.on('error', reject);
        req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
        req.end();
    });
}
function httpPost(path, body) {
    return new Promise((resolve, reject) => {
        const http = require('http');
        const data = JSON.stringify(body);
        const req = http.request(`${exports.DAEMON_URL}${path}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) },
            timeout: 10000,
        }, (res) => {
            let result = '';
            res.on('data', (chunk) => { result += chunk ? chunk.toString() : ''; });
            res.on('end', () => {
                try {
                    resolve(JSON.parse(result));
                }
                catch {
                    resolve(result);
                }
            });
        });
        req.on('error', reject);
        req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
        req.write(data);
        req.end();
    });
}
// ─── Daemon Check ───────────────────────────────────────────────────────────
function isPidAlive(pid) {
    try {
        process.kill(pid, 0);
        return true;
    }
    catch {
        return false;
    }
}
async function isDaemonRunning() {
    try {
        const result = await httpGet('/health');
        return result && result.status === 'ok';
    }
    catch {
        return false;
    }
}
// ─── File Helpers ───────────────────────────────────────────────────────────
function ensureDir(dir) {
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
}
function readJsonSafe(filePath) {
    if (!fs.existsSync(filePath))
        return null;
    try {
        return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
    }
    catch {
        return null;
    }
}
// ─── Output Helpers ─────────────────────────────────────────────────────────
function printHeader(title) {
    console.log();
    console.log(exports.C.bold(`  ${title}`));
    console.log(exports.C.dim(`  ${'─'.repeat(title.length)}`));
    console.log();
}
function printSuccess(msg) {
    console.log(exports.C.success(`  ${msg}`));
}
function printWarning(msg) {
    console.log(exports.C.warn(`  ${msg}`));
}
function printDim(msg) {
    console.log(exports.C.dim(`  ${msg}`));
}
// ─── Error Handler ──────────────────────────────────────────────────────────
async function withError(fn) {
    try {
        await fn();
    }
    catch (e) {
        const msg = e instanceof Error ? e.message : String(e);
        console.log(exports.C.warn('  Failed: ' + msg));
        process.exit(1);
    }
}
//# sourceMappingURL=utils.js.map