import fs from 'fs';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const DEFAULT_FEATURES = ['template-instant', 'hyperloop-stream'];
function readPackageVersion() {
    const candidates = [
        path.join(__dirname, '..', '..', 'package.json'),
        path.join(__dirname, '..', 'package.json'),
    ];
    for (const candidate of candidates) {
        try {
            if (!fs.existsSync(candidate))
                continue;
            const parsed = JSON.parse(fs.readFileSync(candidate, 'utf8'));
            if (parsed.version)
                return String(parsed.version);
        }
        catch {
            // try next candidate
        }
    }
    return '0.0.0';
}
/** Detect iSH/Blink-style iOS terminal sandboxes (override, UA, or Linux-on-iOS release string). */
export function isIOSEnvironment() {
    const override = (process.env.VIGTHORIA_OS_OVERRIDE || '').trim().toLowerCase();
    if (override === 'ios')
        return true;
    const userAgent = (process.env.VIGTHORIA_CLIENT_USER_AGENT || '').trim();
    if (/ipad|iphone|ios/i.test(userAgent))
        return true;
    if (process.platform === 'linux') {
        const release = os.release().toLowerCase();
        if (/ipad|iphone|ios/.test(release))
            return true;
    }
    return false;
}
/** Map Node process.platform/arch to dispatcher gate OS slug. */
export function resolveClientOsSlug() {
    if (isIOSEnvironment()) {
        return process.arch === 'arm64' ? 'ios-arm64' : 'ios-x64';
    }
    if (process.platform === 'win32')
        return 'windows-x86_64';
    if (process.platform === 'darwin') {
        return process.arch === 'arm64' ? 'macos-arm64' : 'macos-x86_64';
    }
    if (process.platform === 'linux') {
        return process.arch === 'arm64' ? 'linux-arm64' : 'linux-x86_64';
    }
    return `${process.platform}-${process.arch}`;
}
export function buildClientManifest(overrides = {}) {
    const ios = isIOSEnvironment() && !overrides.os;
    return {
        product_id: overrides.product_id || 'vigthoria-cli',
        version: overrides.version || readPackageVersion(),
        os: overrides.os || resolveClientOsSlug(),
        execution_mode: overrides.execution_mode || (ios ? 'mobile-terminal-sandbox' : 'local-user-machine'),
        features_allowed: overrides.features_allowed?.length
            ? [...overrides.features_allowed]
            : [...DEFAULT_FEATURES],
    };
}
