"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAzureCustomProviderDiagnostics = void 0;
const node_child_process_1 = require("node:child_process");
const node_util_1 = require("node:util");
const azureSessions_1 = require("../../../util/azureSessions");
const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
const getAzureCustomProviderDiagnostics = async (_req, res) => {
    if (!(0, azureSessions_1.isAzureSessionsConfigured)()) {
        res.status(503).json({
            configured: false,
            message: 'AZURE_SESSIONS_* environment variables are not fully set.',
        });
        return;
    }
    const config = (0, azureSessions_1.getAzureSessionsConfig)();
    let azAccount = null;
    try {
        const { stdout } = await execFileAsync('az', [
            'account',
            'show',
            '--query',
            '{user:user.name, tenant:tenantId, subscription:subscriptionId, userObjectId:user.id}',
            '-o',
            'json',
        ], { timeout: 30000, windowsHide: true });
        azAccount = JSON.parse(stdout.trim());
    }
    catch {
        azAccount = null;
    }
    try {
        const tokenInfo = await (0, azureSessions_1.getAzureSessionsAccessTokenInfo)();
        const isServicePrincipal = (0, azureSessions_1.isServicePrincipalToken)(tokenInfo.claims);
        const tokenOid = tokenInfo.claims?.oid ?? null;
        const tokenAppId = tokenInfo.claims?.appid ?? null;
        res.json({
            configured: true,
            credentialMode: (0, azureSessions_1.shouldUseAzureCliForSessions)() ? 'azure-cli' : 'default-azure-credential',
            subscriptionId: config?.subscriptionId,
            resourceGroup: config?.resourceGroup,
            region: config?.region,
            pythonPool: {
                name: config?.pythonPoolName,
                managementEndpoint: (0, azureSessions_1.getSessionPoolManagementEndpoint)('py'),
            },
            nodePool: {
                name: config?.nodePoolName,
                managementEndpoint: (0, azureSessions_1.getSessionPoolManagementEndpoint)('js'),
            },
            azLoginAccount: azAccount,
            serverToken: {
                credentialSource: tokenInfo.credentialSource,
                identity: tokenInfo.identityLabel,
                oid: tokenOid,
                appId: tokenAppId,
                preferredUsername: tokenInfo.claims?.preferred_username ?? tokenInfo.claims?.upn ?? null,
                audience: tokenInfo.claims?.aud ?? null,
                isServicePrincipal,
            },
            likelyCause: isServicePrincipal
                ? 'Token is app-only (service principal). Assign Session Executor to that SP oid on the pool.'
                : 'User token — if oid matches Entra user, assign Session Executor to that user on the session pool scope (appid in token is normal for az cli).',
            fixOptionA: isServicePrincipal
                ? {
                    title: 'Assign role to the service principal (fastest)',
                    steps: [
                        `Portal → trusys-python-pool → IAM → Add role assignment → Azure ContainerApps Session Executor`,
                        `Members → Enterprise applications / App registrations → find app id ${tokenAppId}`,
                        `Or search by object id ${tokenOid}`,
                        'Scope: this session pool. Repeat for trusys-js-pool.',
                    ],
                }
                : null,
            fixOptionB: isServicePrincipal
                ? {
                    title: 'Use your user account instead (if you already assigned IAM to yourself)',
                    steps: [
                        'Terminal: az logout',
                        'Terminal: az login   (browser — sign in as ritik@spydra.app, NOT service principal)',
                        'az account set --subscription 05e49936-9c94-454b-8796-6008315e285c',
                        'Restart npm run dev:server',
                        'GET /diagnostics again — serverToken.isServicePrincipal should be false',
                    ],
                }
                : null,
            codeExecutionNote: 'Trusys uses synchronous POST /executions only (api-version 2025-10-02-preview, max 220s). JavaScript uploads with package.json dependencies must include node_modules/ in the zip (max 100 MB upload).',
            iamChecklist: [
                'Portal → trusys-python-pool → Access control (IAM) → Role assignments',
                'Role: Azure ContainerApps Session Executor',
                `Member object id must match serverToken.oid (${tokenOid ?? 'see above'})`,
                isServicePrincipal
                    ? 'Token is app-only SP — assign IAM to serverToken.oid (the SP)'
                    : 'User token: appid in JWT is normal (Azure CLI client) — IAM member oid must be serverToken.oid',
                'Scope: this session pool (trusys-python-pool), not only the resource group',
                'Repeat for trusys-js-pool when testing JavaScript',
            ],
        });
    }
    catch (error) {
        res.status(500).json({
            configured: true,
            credentialMode: (0, azureSessions_1.shouldUseAzureCliForSessions)() ? 'azure-cli' : 'default-azure-credential',
            azLoginAccount: azAccount,
            error: error instanceof Error ? error.message : String(error),
        });
    }
};
exports.getAzureCustomProviderDiagnostics = getAzureCustomProviderDiagnostics;
//# sourceMappingURL=diagnostics.js.map