#!/usr/bin/env node
"use strict";
/**
 * W2: `packs` subcommand for the @connexum/ai-governance CLI.
 *
 * Usage:
 *   npx @connexum/ai-governance packs select --project <id> --packs hipaa,ferpa,soc2
 *   npx @connexum/ai-governance packs get    --project <id>
 *   npx @connexum/ai-governance packs upgrade --project <id> --pack hipaa --version 1.1.0
 *
 * All commands require:
 *   --api-url <url>      Governance server URL (default: http://localhost:3200)
 *   --license-key <key>  Bearer JWT (or set CONNEXUM_LICENSE env var)
 *
 * Exit codes:
 *   0 -- success
 *   1 -- usage error
 *   2 -- API error
 *
 * @connexum/ai-governance
 */
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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.runPacksCommand = runPacksCommand;
const https = __importStar(require("node:https"));
const http = __importStar(require("node:http"));
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function parseArgs(argv) {
    const out = {};
    for (let i = 0; i < argv.length; i++) {
        const arg = argv[i];
        if (arg.startsWith('--')) {
            const key = arg.slice(2);
            const next = argv[i + 1];
            if (next && !next.startsWith('--')) {
                out[key] = next;
                i++;
            }
            else {
                out[key] = true;
            }
        }
    }
    return out;
}
function printUsage() {
    process.stdout.write(`
Usage: npx @connexum/ai-governance packs <subcommand> [options]

Subcommands:
  select   Set the active compliance packs for a project
  get      Show the current pack selection for a project
  upgrade  Pin a project to a specific pack version (W3)

Options:
  --project <id>      Project ID (required for all subcommands)
  --packs <list>      Comma-separated pack IDs, e.g. hipaa,ferpa,soc2
  --pack <id>         Single pack ID (for upgrade)
  --version <semver>  Semver string for version pin (for upgrade)
  --api-url <url>     Governance server URL (default: http://localhost:3200)
  --license-key <key> Bearer JWT (or CONNEXUM_LICENSE env var)
  --help, -h          Show this help

Examples:
  npx @connexum/ai-governance packs select --project proj_abc --packs hipaa,ferpa,soc2
  npx @connexum/ai-governance packs get --project proj_abc
  npx @connexum/ai-governance packs upgrade --project proj_abc --pack hipaa --version 1.1.0
`.trim() + '\n');
}
function request(method, url, body, licenseKey) {
    return new Promise((resolve, reject) => {
        const parsed = new URL(url);
        const isHttps = parsed.protocol === 'https:';
        const mod = isHttps ? https : http;
        const bodyStr = body !== undefined ? JSON.stringify(body) : undefined;
        const req = mod.request({
            hostname: parsed.hostname,
            port: parsed.port || (isHttps ? 443 : 80),
            path: parsed.pathname + (parsed.search ?? ''),
            method,
            headers: {
                'Authorization': `Bearer ${licenseKey}`,
                'Content-Type': 'application/json',
                ...(bodyStr ? { 'Content-Length': Buffer.byteLength(bodyStr) } : {}),
            },
        }, (res) => {
            const chunks = [];
            res.on('data', (c) => chunks.push(c));
            res.on('end', () => {
                try {
                    const text = Buffer.concat(chunks).toString('utf8');
                    resolve({ status: res.statusCode ?? 0, body: JSON.parse(text) });
                }
                catch {
                    resolve({ status: res.statusCode ?? 0, body: null });
                }
            });
        });
        req.on('error', reject);
        if (bodyStr)
            req.write(bodyStr);
        req.end();
    });
}
// ---------------------------------------------------------------------------
// Subcommand: packs select
// ---------------------------------------------------------------------------
async function selectPacks(args) {
    const projectId = args['project'];
    const packsArg = args['packs'];
    const apiUrl = args['api-url'] ?? 'http://localhost:3200';
    const licenseKey = args['license-key'] ?? process.env['CONNEXUM_LICENSE'] ?? '';
    if (!projectId) {
        process.stderr.write('Error: --project <id> is required\n');
        process.exit(1);
    }
    if (!packsArg) {
        process.stderr.write('Error: --packs <comma-separated list> is required\n');
        process.exit(1);
    }
    if (!licenseKey) {
        process.stderr.write('Error: --license-key or CONNEXUM_LICENSE env var is required\n');
        process.exit(1);
    }
    const packIds = packsArg.split(',').map((p) => p.trim()).filter(Boolean);
    const url = `${apiUrl.replace(/\/$/, '')}/api/v1/projects/${encodeURIComponent(projectId)}/packs`;
    process.stdout.write(`Selecting packs [${packIds.join(', ')}] for project ${projectId}...\n`);
    let result;
    try {
        result = await request('POST', url, { packIds }, licenseKey);
    }
    catch (err) {
        process.stderr.write(`Error: could not connect to governance server at ${apiUrl}: ${err.message}\n`);
        process.exit(2);
    }
    if (result.status >= 400) {
        const errMsg = result.body?.error ?? result.status;
        process.stderr.write(`Error (HTTP ${result.status}): ${errMsg}\n`);
        process.exit(2);
    }
    const data = result.body;
    process.stdout.write(`Pack selection updated successfully.\n`);
    process.stdout.write(`  Project:  ${data.projectId}\n`);
    process.stdout.write(`  Packs:    ${data.selectedPackIds.join(', ') || '(none)'}\n`);
    process.stdout.write(`  Updated:  ${data.updatedAt}\n`);
    process.stdout.write(`  By:       ${data.updatedBy}\n`);
}
// ---------------------------------------------------------------------------
// Subcommand: packs get
// ---------------------------------------------------------------------------
async function getPacks(args) {
    const projectId = args['project'];
    const apiUrl = args['api-url'] ?? 'http://localhost:3200';
    const licenseKey = args['license-key'] ?? process.env['CONNEXUM_LICENSE'] ?? '';
    if (!projectId) {
        process.stderr.write('Error: --project <id> is required\n');
        process.exit(1);
    }
    if (!licenseKey) {
        process.stderr.write('Error: --license-key or CONNEXUM_LICENSE env var is required\n');
        process.exit(1);
    }
    const url = `${apiUrl.replace(/\/$/, '')}/api/v1/projects/${encodeURIComponent(projectId)}/packs`;
    let result;
    try {
        result = await request('GET', url, undefined, licenseKey);
    }
    catch (err) {
        process.stderr.write(`Error: could not connect to governance server at ${apiUrl}: ${err.message}\n`);
        process.exit(2);
    }
    if (result.status >= 400) {
        const errMsg = result.body?.error ?? result.status;
        process.stderr.write(`Error (HTTP ${result.status}): ${errMsg}\n`);
        process.exit(2);
    }
    const data = result.body;
    const versions = data.selectedPackVersions;
    const packs = data.selectedPackIds ?? [];
    process.stdout.write(`Pack selection for project ${data.projectId}:\n`);
    if (packs.length === 0) {
        process.stdout.write('  (no packs selected)\n');
    }
    else {
        for (const packId of packs) {
            const ver = versions?.[packId];
            process.stdout.write(`  ${packId}${ver ? ` @ ${ver}` : ''}\n`);
        }
    }
    process.stdout.write(`  Last updated: ${data.updatedAt} by ${data.updatedBy}\n`);
}
// ---------------------------------------------------------------------------
// Subcommand: packs upgrade
// ---------------------------------------------------------------------------
async function upgradePack(args) {
    const projectId = args['project'];
    const packId = args['pack'];
    const version = args['version'];
    const apiUrl = args['api-url'] ?? 'http://localhost:3200';
    const licenseKey = args['license-key'] ?? process.env['CONNEXUM_LICENSE'] ?? '';
    if (!projectId) {
        process.stderr.write('Error: --project <id> is required\n');
        process.exit(1);
    }
    if (!packId) {
        process.stderr.write('Error: --pack <id> is required\n');
        process.exit(1);
    }
    if (!version) {
        process.stderr.write('Error: --version <semver> is required\n');
        process.exit(1);
    }
    if (!licenseKey) {
        process.stderr.write('Error: --license-key or CONNEXUM_LICENSE env var is required\n');
        process.exit(1);
    }
    const url = `${apiUrl.replace(/\/$/, '')}/api/v1/projects/${encodeURIComponent(projectId)}/packs/${encodeURIComponent(packId)}/upgrade`;
    process.stdout.write(`Upgrading pack ${packId} on project ${projectId} to version ${version}...\n`);
    let result;
    try {
        result = await request('POST', url, { version }, licenseKey);
    }
    catch (err) {
        process.stderr.write(`Error: could not connect to governance server at ${apiUrl}: ${err.message}\n`);
        process.exit(2);
    }
    if (result.status >= 400) {
        const errMsg = result.body?.error ?? result.status;
        process.stderr.write(`Error (HTTP ${result.status}): ${errMsg}\n`);
        process.exit(2);
    }
    const data = result.body;
    process.stdout.write(`Pack version updated:\n`);
    process.stdout.write(`  Pack:     ${data.packId}\n`);
    process.stdout.write(`  Previous: ${data.previousVersion ?? '(none)'}\n`);
    process.stdout.write(`  New:      ${data.newVersion}\n`);
    process.stdout.write(`  Updated:  ${data.updatedAt}\n`);
}
// ---------------------------------------------------------------------------
// Entrypoint (called from CLI index.ts when command === 'packs')
// ---------------------------------------------------------------------------
async function runPacksCommand(argv) {
    const subcommand = argv[0];
    const args = parseArgs(argv.slice(1));
    if (args['help'] || args['h'] || !subcommand) {
        printUsage();
        process.exit(0);
    }
    switch (subcommand) {
        case 'select':
            await selectPacks(args);
            break;
        case 'get':
            await getPacks(args);
            break;
        case 'upgrade':
            await upgradePack(args);
            break;
        default:
            process.stderr.write(`Unknown packs subcommand: '${subcommand}'\n`);
            printUsage();
            process.exit(1);
    }
}
//# sourceMappingURL=packs.js.map