"use strict";
/**
 * Antigravity OAuth Responsibility Gate
 *
 * Enforces explicit user acknowledgement for Antigravity OAuth usage.
 * This is used by:
 * - CLI OAuth flow (`ccs agy --auth`)
 * - CLI runtime flow (`ccs agy`)
 * - Dashboard auth endpoints (server-side payload validation)
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensureCliAntigravityResponsibility = exports.validateAntigravityRiskAcknowledgement = exports.hasAntigravityRiskAcceptanceFlag = exports.isAntigravityResponsibilityBypassEnabled = exports.ANTIGRAVITY_ACCEPT_RISK_FLAGS = exports.ANTIGRAVITY_ACK_PHRASE = exports.RISK_ACK_PHRASE = exports.ANTIGRAVITY_ACK_VERSION = exports.ANTIGRAVITY_RISK_ISSUE_URL = void 0;
const readline_1 = require("readline");
const ui_1 = require("../../utils/ui");
const config_loader_facade_1 = require("../../config/config-loader-facade");
exports.ANTIGRAVITY_RISK_ISSUE_URL = 'https://github.com/kaitranntt/ccs/issues/509';
exports.ANTIGRAVITY_ACK_VERSION = '2026-02-24-antigravity-oauth-v2';
exports.RISK_ACK_PHRASE = 'I ACCEPT RISK';
exports.ANTIGRAVITY_ACK_PHRASE = exports.RISK_ACK_PHRASE;
exports.ANTIGRAVITY_ACCEPT_RISK_FLAGS = ['--accept-agr-risk', '--accept-antigravity-risk'];
function normalizePhrase(value) {
    return value.trim().replace(/\s+/g, ' ').toUpperCase();
}
function isTruthyEnv(value) {
    if (!value)
        return false;
    const normalized = value.trim().toLowerCase();
    return normalized === '1' || normalized === 'true' || normalized === 'yes';
}
function isAntigravityResponsibilityBypassEnabled() {
    if (isTruthyEnv(process.env.CCS_ACCEPT_AGY_RISK)) {
        return true;
    }
    try {
        const safety = (0, config_loader_facade_1.getCliproxySafetyConfig)();
        return safety.antigravity_ack_bypass === true;
    }
    catch {
        return false;
    }
}
exports.isAntigravityResponsibilityBypassEnabled = isAntigravityResponsibilityBypassEnabled;
function askQuestion(rl, prompt) {
    return new Promise((resolve) => {
        let settled = false;
        const onClose = () => {
            if (!settled) {
                settled = true;
                resolve(null);
            }
        };
        rl.once('close', onClose);
        rl.question(prompt, (answer) => {
            if (settled)
                return;
            settled = true;
            rl.removeListener('close', onClose);
            resolve(answer.trim());
        });
    });
}
async function askYesNoStep(rl, step, message) {
    while (true) {
        const answer = await askQuestion(rl, `[?] ${step}\n    ${message}\n    Type YES to continue (NO to cancel): `);
        if (answer === null)
            return false;
        const normalized = answer.toUpperCase();
        if (normalized === 'YES')
            return true;
        if (normalized === 'NO' || normalized === 'N' || normalized === '')
            return false;
        console.error((0, ui_1.warn)('Please type YES or NO.'));
    }
}
async function askResponsibilityPhrase(rl) {
    for (let attempt = 0; attempt < 3; attempt++) {
        const answer = await askQuestion(rl, `[?] Step 4/4\n    Type exactly "${exports.ANTIGRAVITY_ACK_PHRASE}": `);
        if (answer === null || answer === '')
            return false;
        if (normalizePhrase(answer) === exports.ANTIGRAVITY_ACK_PHRASE) {
            return true;
        }
        console.error((0, ui_1.warn)('Phrase mismatch. Try again.'));
    }
    return false;
}
function printResponsibilityHeader(context) {
    const contextLine = context === 'oauth'
        ? 'You are starting Antigravity OAuth account authorization.'
        : 'You are starting a live Antigravity CLI session (ccs agy).';
    console.error('');
    console.error('╔══════════════════════════════════════════════════════════════════════╗');
    console.error('║ Antigravity Responsibility Confirmation (Mandatory)                  ║');
    console.error('╚══════════════════════════════════════════════════════════════════════╝');
    console.error(`    ${contextLine}`);
    console.error('    Antigravity has active ban/suspension patterns for risky OAuth usage.');
    console.error(`    Policy issue: ${exports.ANTIGRAVITY_RISK_ISSUE_URL}`);
    console.error('');
}
function hasAntigravityRiskAcceptanceFlag(args) {
    return args.some((arg) => exports.ANTIGRAVITY_ACCEPT_RISK_FLAGS.includes(arg));
}
exports.hasAntigravityRiskAcceptanceFlag = hasAntigravityRiskAcceptanceFlag;
function validateAntigravityRiskAcknowledgement(payload) {
    if (!payload || typeof payload !== 'object') {
        return {
            valid: false,
            error: 'Antigravity OAuth requires a full responsibility acknowledgement payload.',
        };
    }
    const data = payload;
    if (data.version !== exports.ANTIGRAVITY_ACK_VERSION) {
        return {
            valid: false,
            error: 'Antigravity acknowledgement version mismatch. Re-open add account and try again.',
        };
    }
    if (!data.reviewedIssue509 || !data.understandsBanRisk || !data.acceptsFullResponsibility) {
        return {
            valid: false,
            error: 'Complete all Antigravity responsibility checklist steps before authenticating.',
        };
    }
    if (typeof data.typedPhrase !== 'string' ||
        normalizePhrase(data.typedPhrase) !== exports.ANTIGRAVITY_ACK_PHRASE) {
        return {
            valid: false,
            error: `Type exact acknowledgement phrase: "${exports.ANTIGRAVITY_ACK_PHRASE}".`,
        };
    }
    return { valid: true };
}
exports.validateAntigravityRiskAcknowledgement = validateAntigravityRiskAcknowledgement;
async function ensureCliAntigravityResponsibility(options) {
    if (options.acceptedByFlag || isAntigravityResponsibilityBypassEnabled()) {
        return true;
    }
    if (!process.stdin.isTTY || !process.stderr.isTTY) {
        console.error((0, ui_1.fail)('Antigravity responsibility acknowledgement required.'));
        console.error('    Re-run interactively and complete the 4-step confirmation.');
        console.error('    Non-interactive override: --accept-agr-risk');
        return false;
    }
    printResponsibilityHeader(options.context);
    const rl = (0, readline_1.createInterface)({
        input: process.stdin,
        output: process.stderr,
    });
    try {
        const step1 = await askYesNoStep(rl, 'Step 1/4', 'I reviewed issue #509 and understand AGY OAuth can trigger bans/suspensions.');
        if (!step1)
            return false;
        const step2 = await askYesNoStep(rl, 'Step 2/4', 'I understand this OAuth operation is my own decision and I choose to continue.');
        if (!step2)
            return false;
        const step3 = await askYesNoStep(rl, 'Step 3/4', 'I accept that CCS provides no responsibility coverage for account loss, bans, or suspension.');
        if (!step3)
            return false;
        const step4 = await askResponsibilityPhrase(rl);
        if (!step4)
            return false;
        console.error((0, ui_1.ok)('Antigravity responsibility acknowledgement accepted for this command.'));
        console.error((0, ui_1.info)('Proceeding with Antigravity flow...'));
        return true;
    }
    finally {
        rl.close();
    }
}
exports.ensureCliAntigravityResponsibility = ensureCliAntigravityResponsibility;
//# sourceMappingURL=antigravity-responsibility.js.map