#!/usr/bin/env npx tsx
"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
const util_1 = require("util");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const execAsync = (0, util_1.promisify)(child_process_1.exec);
async function testCliIntegration() {
    console.log('\n=== CLI Integration Test ===\n');
    const configDir = path.join(process.cwd(), '.knowhow');
    const jwtFile = path.join(configDir, '.jwt');
    let testResults = [];
    try {
        if (fs.existsSync(jwtFile)) {
            fs.unlinkSync(jwtFile);
            console.log('🧹 Cleaned up existing JWT file\n');
        }
        console.log('=== Test 1: Browser Login as Default ===');
        console.log('Testing: knowhow login (should use browser login)');
        console.log('Note: This will open your browser - please complete authentication\n');
        try {
            const { stdout, stderr } = await execAsync('npm run build && node dist/cli.js login', {
                timeout: 120000
            });
            console.log('Command output:', stdout);
            if (stderr)
                console.log('Command stderr:', stderr);
            if (fs.existsSync(jwtFile)) {
                const jwtContent = fs.readFileSync(jwtFile, 'utf8');
                if (jwtContent.split('.').length === 3) {
                    console.log('✅ Test 1 PASSED: Browser login created valid JWT');
                    testResults.push('✅ Browser login as default: PASSED');
                }
                else {
                    console.log('❌ Test 1 FAILED: Invalid JWT created');
                    testResults.push('❌ Browser login as default: FAILED (invalid JWT)');
                }
            }
            else {
                console.log('❌ Test 1 FAILED: No JWT file created');
                testResults.push('❌ Browser login as default: FAILED (no JWT file)');
            }
        }
        catch (error) {
            if (error.killed && error.signal === 'SIGTERM') {
                console.log('⚠️  Test 1 TIMEOUT: User may not have completed authentication');
                testResults.push('⚠️  Browser login as default: TIMEOUT');
            }
            else {
                console.log('❌ Test 1 ERROR:', error.message);
                testResults.push('❌ Browser login as default: ERROR');
            }
        }
        if (fs.existsSync(jwtFile)) {
            fs.unlinkSync(jwtFile);
        }
        console.log('\n=== Test 2: Legacy JWT Input ===');
        console.log('Testing: knowhow login --jwt (should prompt for manual JWT input)');
        try {
            const { stdout, stderr } = await execAsync('echo "" | npm run build && echo "" | node dist/cli.js login --jwt', {
                timeout: 10000
            });
            console.log('Command output:', stdout);
            if (stderr)
                console.log('Command stderr:', stderr);
            if (stdout.includes('JWT') || stdout.includes('token') || stderr.includes('JWT') || stderr.includes('token')) {
                console.log('✅ Test 2 PASSED: --jwt flag triggers manual JWT input');
                testResults.push('✅ Legacy JWT input: PASSED');
            }
            else {
                console.log('❌ Test 2 FAILED: --jwt flag not working correctly');
                testResults.push('❌ Legacy JWT input: FAILED');
            }
        }
        catch (error) {
            if (error.message.includes('JWT') || error.message.includes('token')) {
                console.log('✅ Test 2 PASSED: --jwt flag triggered JWT input prompt');
                testResults.push('✅ Legacy JWT input: PASSED');
            }
            else {
                console.log('❌ Test 2 FAILED:', error.message);
                testResults.push('❌ Legacy JWT input: FAILED');
            }
        }
        console.log('\n=== Test 3: Command Help ===');
        console.log('Testing: knowhow login --help');
        try {
            const { stdout, stderr } = await execAsync('npm run build && node dist/cli.js login --help');
            console.log('Help output:', stdout);
            if (stdout.includes('--jwt') && stdout.includes('browser')) {
                console.log('✅ Test 3 PASSED: Help shows both browser and JWT options');
                testResults.push('✅ Command help: PASSED');
            }
            else {
                console.log('❌ Test 3 FAILED: Help missing expected options');
                testResults.push('❌ Command help: FAILED');
            }
        }
        catch (error) {
            console.log('❌ Test 3 ERROR:', error.message);
            testResults.push('❌ Command help: ERROR');
        }
    }
    catch (error) {
        console.error('❌ Test suite failed:', error.message);
    }
    console.log('\n=== Test Summary ===');
    testResults.forEach(result => console.log(result));
    const passedTests = testResults.filter(r => r.includes('PASSED')).length;
    const totalTests = testResults.length;
    console.log(`\nResults: ${passedTests}/${totalTests} tests passed`);
    if (passedTests === totalTests) {
        console.log('🎉 All CLI integration tests PASSED!');
        process.exit(0);
    }
    else {
        console.log('❌ Some CLI integration tests FAILED');
        process.exit(1);
    }
}
process.on('SIGINT', () => {
    console.log('\n\n🛑 Test interrupted by user (Ctrl+C)');
    process.exit(0);
});
testCliIntegration().catch((error) => {
    console.error('Unhandled error:', error);
    process.exit(1);
});
//# sourceMappingURL=test_cli_integration.js.map