/**
 * AmazonQDeveloperIdeAdapter -- Amazon Q Developer adapter.
 *
 * Amazon Q Developer (formerly CodeWhisperer) ships with every AWS Bedrock
 * shop. This adapter is the natural pair with the Bedrock AgentCore
 * orchestrator adapter (P3-SUB-ADAPT-03, src/orchestrator-adapters/
 * bedrock-agentcore.ts): the same BAA region list applies directly.
 *
 * Hook surfaces:
 *   Standard six (shared with GitHub Copilot contract):
 *   completionRequested(file, cursor, context) -- pre-completion gate.
 *   completionReceived(completion, context) -- post-completion ingress.
 *   chatRequested(prompt, context) -- pre-chat gate.
 *   chatReceived(response) -- post-chat ingress classification.
 *   suggestionAccepted(suggestion, targetFile) -- audit on acceptance.
 *   suggestionRejected(suggestion, reason) -- optional audit.
 *
 *   Amazon Q-specific surfaces:
 *   awsResourceOperationRequested(resource, operation) -- Q Developer's
 *     "agent for AWS" feature can create/modify/delete AWS resources.
 *     High-risk egress path routed through G4 Destructive Command Guard
 *     equivalent. (PT-ADAPT-AMAZONQ-3)
 *   iamPolicyGenerationRequested(role, intent) -- Q Developer writes IAM
 *     policies. Adapter runs a policy-safety classifier (wildcards, missing
 *     MFA, etc.) before return. Under PCI/HIPAA, routes to named reviewer.
 *     (PT-ADAPT-AMAZONQ-2)
 *   codeTransformRequested(project, targetVersion) -- whole-project Java
 *     modernization. Surfaces as bulk refactor subject to pack-binding
 *     rules. Audit chain needs project-level provenance.
 *
 * AWS-specific considerations:
 *   - Q Developer runs on AWS native; Bedrock BAA region list applies.
 *     (PT-ADAPT-AMAZONQ-1)
 *   - IAM policy generation output classifies as "infrastructure-change"
 *     DataClass; routes to named AWS reviewer when PCI or HIPAA is bound.
 *   - Code Transform workflows touch source code at scale; audit chain
 *     carries project-level provenance (projectName + targetVersion).
 *
 * Spec: P3-SUB-IDE-04
 *
 * @connexum/ai-governance
 */
import { BaseIdeAdapter } from './base.js';
import { IdeAttributionError, IdeUnsupportedError, } from './index.js';
import { buildIdeAuditEvent } from './shared.js';
// ---------------------------------------------------------------------------
// Bedrock BAA regions (shared source of truth with Bedrock AgentCore adapter)
//
// These regions have data-processing commitments suitable for HIPAA BAA
// coverage when an AWS BAA is in place.
//
// Reference: https://aws.amazon.com/compliance/hipaa-eligible-services-reference/
// (Amazon Bedrock is listed as HIPAA eligible in the following regions)
// ---------------------------------------------------------------------------
export const AMAZON_Q_BAA_REGIONS = [
    'us-east-1',
    'us-east-2',
    'us-west-2',
    'eu-west-1',
    'eu-west-2',
    'eu-central-1',
    'ap-southeast-2',
];
const DESTRUCTIVE_AWS_OPERATIONS = new Set([
    'DeleteBucket',
    'DeleteObject',
    'DeleteFunction',
    'DeleteRole',
    'DetachRolePolicy',
    'DeleteSecurityGroup',
    'TerminateInstances',
    'DeleteCluster',
    'DeleteTable', // DynamoDB
    'DeleteDatabase', // RDS
    'DeleteStack', // CloudFormation
    'PurgeQueue', // SQS
    'DeleteTopic', // SNS
    'DeleteSecret', // Secrets Manager
    'DisableKey', // KMS
    'ScheduleKeyDeletion', // KMS
]);
// ---------------------------------------------------------------------------
// IAM policy safety patterns
//
// These patterns in a generated IAM policy indicate overly-broad permissions
// or missing security conditions that should be flagged.
// ---------------------------------------------------------------------------
const IAM_UNSAFE_PATTERNS = [
    {
        name: 'wildcard-action',
        re: /"Action"\s*:\s*"\*"/,
    },
    {
        name: 'wildcard-resource',
        re: /"Resource"\s*:\s*"\*"/,
    },
    {
        name: 'all-actions-on-iam',
        re: /"Action"\s*:\s*"iam:\*"/,
    },
    {
        name: 'all-actions-on-s3',
        re: /"Action"\s*:\s*"s3:\*"/,
    },
    {
        name: 'allow-all-principals',
        re: /"Principal"\s*:\s*"\*"/,
    },
    {
        name: 'no-mfa-condition',
        // Heuristic: Effect Allow + Action on iam: but no MFA condition.
        // Actual enforcement is in the classifier method below.
        re: /"Effect"\s*:\s*"Allow"[\s\S]{0,200}"iam:/,
    },
    {
        name: 'no-condition-block',
        // Policy has no Condition block at all (heuristic for missing MFA/IP constraints)
        re: /"Statement"\s*:\s*\[[\s\S]*?"Effect"\s*:\s*"Allow"(?![\s\S]*?"Condition")/,
    },
];
// ---------------------------------------------------------------------------
// Secret patterns (same subset as other IDE adapters)
// ---------------------------------------------------------------------------
const AQ_SECRET_PATTERNS = [
    { name: 'AWS access key', re: /AKIA[0-9A-Z]{16}/ },
    { name: 'GitHub PAT', re: /ghp_[0-9A-Za-z]{36}|github_pat_[0-9A-Za-z_]{82}/ },
    { name: 'Anthropic API key', re: /sk-ant-[0-9A-Za-z\-_]{20,}/ },
    { name: 'OpenAI API key', re: /sk-[0-9A-Za-z]{20,}/ },
    { name: 'Private key header', re: /-----BEGIN (RSA|EC|OPENSSH) PRIVATE KEY-----/ },
    { name: 'Generic secret env var', re: /(SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)\s*=\s*["']?\S{8,}["']?/i },
    { name: 'Bearer token', re: /Authorization:\s*Bearer\s+[0-9A-Za-z\-._~+/]{20,}/i },
    { name: 'Database URL with creds', re: /(postgres|mysql|mongodb|redis):\/\/[^:]+:[^@]+@/ },
];
// ---------------------------------------------------------------------------
// PHI indicators
// ---------------------------------------------------------------------------
const AQ_PHI_INDICATORS = [
    /\bpatient[_\s]?(id|name|dob|ssn|mrn|record)\b/i,
    /\bdiagnos(is|es)\b/i,
    /\bprescription\b/i,
    /\bmedical[_\s]?record\b/i,
    /\bhealth[_\s]?plan\b/i,
    /\bssn\b/,
    /\bdate[_\s]?of[_\s]?birth\b/i,
    /\btreatment[_\s]?plan\b/i,
    /\bhipaa\b/i,
    /\bphi\b/,
];
// ---------------------------------------------------------------------------
// AmazonQDeveloperIdeAdapter
// ---------------------------------------------------------------------------
export class AmazonQDeveloperIdeAdapter extends BaseIdeAdapter {
    adapterId = 'amazon-q-developer';
    ideId = 'amazon-q-developer';
    aqConfig = null;
    // ---------------------------------------------------------------------------
    // Lifecycle
    // ---------------------------------------------------------------------------
    initialize(config) {
        super.initialize(config);
        this.aqConfig = config;
        const region = this.aqConfig.awsRegion ?? 'us-east-1';
        this.emit(buildIdeAuditEvent('ide:session-open', {
            ideId: this.ideId,
            adapterId: this.adapterId,
            detail: `AmazonQDeveloperIdeAdapter initialized. ` +
                `Region: ${region}. ` +
                `BAA eligible region: ${AMAZON_Q_BAA_REGIONS.includes(region)}.`,
            data: { region, baaEligible: AMAZON_Q_BAA_REGIONS.includes(region) },
        }));
    }
    // ---------------------------------------------------------------------------
    // IdeAdapter: resolveUserIdentity
    // ---------------------------------------------------------------------------
    async resolveUserIdentity(session) {
        this.ensureInitialized();
        const fromSession = session.identity?.userId?.trim();
        if (fromSession) {
            const identity = {
                userId: fromSession,
                email: session.identity?.email,
                orgId: session.identity?.orgId,
                attributionMethod: 'cursor-composer',
            };
            this.emitIdentityResolved(identity.userId, session.clientSessionId);
            return identity;
        }
        const allowAnon = this.config?.allowAnonymousIdeSessions === true;
        if (allowAnon) {
            const anon = { userId: 'anonymous', attributionMethod: 'cursor-composer' };
            this.emitIdentityResolved(anon.userId, session.clientSessionId);
            return anon;
        }
        this.emitIdentityUnresolved(session.clientSessionId, 'AmazonQDeveloperIdeAdapter: no user identity in session context.');
        throw new IdeAttributionError({
            message: 'AmazonQDeveloperIdeAdapter: cannot resolve user identity. Provide a userId in ' +
                'session.identity.userId (the AWS SSO or IAM Identity Center user ID), or set ' +
                'allowAnonymousIdeSessions: true in adapter config.',
            ideId: this.ideId,
            adapterId: this.adapterId,
        });
    }
    // ---------------------------------------------------------------------------
    // IdeAdapter: interceptToolInvocation
    //
    // Normalised tool invocations:
    //   Standard six:
    //   'aq:completion-requested'          -> completionRequested gate
    //   'aq:completion-received'           -> completionReceived ingress
    //   'aq:chat-requested'                -> chatRequested gate
    //   'aq:chat-received'                 -> chatReceived ingress
    //   'aq:suggestion-accepted'           -> audit
    //   'aq:suggestion-rejected'           -> audit
    //
    //   Amazon Q-specific:
    //   'aq:aws-resource-operation'        -> awsResourceOperationRequested gate
    //   'aq:iam-policy-generation'         -> iamPolicyGenerationRequested gate
    //   'aq:code-transform-requested'      -> codeTransformRequested gate
    // ---------------------------------------------------------------------------
    async interceptToolInvocation(ctx) {
        this.ensureInitialized();
        switch (ctx.tool) {
            case 'aq:completion-requested':
                return this._gateCompletionRequest(ctx);
            case 'aq:completion-received':
                return this._scanCompletionResponse(ctx);
            case 'aq:chat-requested':
                return this._gateChatRequest(ctx);
            case 'aq:chat-received':
                return this._scanChatResponse(ctx);
            case 'aq:suggestion-accepted':
                return this._auditSuggestionAccepted(ctx);
            case 'aq:suggestion-rejected':
                return this._auditSuggestionRejected(ctx);
            case 'aq:aws-resource-operation':
                return this._gateAwsResourceOperation(ctx);
            case 'aq:iam-policy-generation':
                return this._gateIamPolicyGeneration(ctx);
            case 'aq:code-transform-requested':
                return this._gateCodeTransform(ctx);
            default:
                this.emit(buildIdeAuditEvent('ide:tool-invocation-approved', {
                    ideId: this.ideId,
                    adapterId: this.adapterId,
                    sessionId: ctx.sessionHandle.sessionId,
                    initiatingUserId: ctx.initiatingUser.userId,
                    tool: ctx.tool,
                    detail: `AmazonQDeveloperIdeAdapter: unknown surface '${ctx.tool}' -- allowed with audit.`,
                }));
                return this.routeToolInvocation(ctx, {
                    decision: 'ALLOW',
                    reason: `Unknown Amazon Q surface '${ctx.tool}' permitted with audit.`,
                });
        }
    }
    // ---------------------------------------------------------------------------
    // Hook: completionRequested
    // ---------------------------------------------------------------------------
    async _gateCompletionRequest(ctx) {
        const surroundingContext = String(ctx.input['surroundingContext'] ?? ctx.input['context'] ?? '');
        const filePath = String(ctx.input['filePath'] ?? ctx.input['file_path'] ?? '');
        // BAA region check under HIPAA
        const regionDecision = this._checkBaaRegion(ctx);
        if (regionDecision)
            return regionDecision;
        const secretMatch = this._scanForSecrets(surroundingContext);
        if (secretMatch) {
            return this.routeToolInvocation(ctx, {
                decision: 'DENY',
                reason: `Completion blocked: secret pattern '${secretMatch}' in surrounding context (${filePath}).`,
                metadata: { filePath, secretPattern: secretMatch },
            });
        }
        if (this._isHipaaOrPciBinding()) {
            const phiMatch = this._scanForPhiIndicators(surroundingContext);
            if (phiMatch) {
                const tier = this.aqConfig?.hipaaReviewerTier ?? 'T2_LEAD';
                return this.routeToolInvocation(ctx, {
                    decision: 'REQUIRE_APPROVAL',
                    reason: `Completion routed for review: PHI indicator '${phiMatch}' in context. Tier: ${tier}.`,
                    metadata: { filePath, phiIndicator: phiMatch, tier },
                });
            }
        }
        return this.routeToolInvocation(ctx, {
            decision: 'ALLOW',
            reason: `Completion request permitted by AmazonQDeveloperIdeAdapter.`,
            metadata: { filePath },
        });
    }
    // ---------------------------------------------------------------------------
    // Hook: completionReceived
    // ---------------------------------------------------------------------------
    async _scanCompletionResponse(ctx) {
        const completionText = String(ctx.input['completionText'] ?? ctx.input['completion'] ?? '');
        const secretMatch = this._scanForSecrets(completionText);
        if (secretMatch) {
            return this.routeToolInvocation(ctx, {
                decision: 'DENY',
                reason: `Completion response blocked: secret pattern '${secretMatch}' in returned code.`,
                metadata: { secretPattern: secretMatch },
            });
        }
        return this.routeToolInvocation(ctx, {
            decision: 'ALLOW',
            reason: 'Completion response passed Amazon Q secret-scan ingress.',
        });
    }
    // ---------------------------------------------------------------------------
    // Hook: chatRequested
    // ---------------------------------------------------------------------------
    async _gateChatRequest(ctx) {
        const promptText = String(ctx.input['promptText'] ?? ctx.input['prompt'] ?? '');
        const regionDecision = this._checkBaaRegion(ctx);
        if (regionDecision)
            return regionDecision;
        const secretMatch = this._scanForSecrets(promptText);
        if (secretMatch) {
            return this.routeToolInvocation(ctx, {
                decision: 'DENY',
                reason: `Chat request blocked: secret pattern '${secretMatch}' in prompt.`,
                metadata: { secretPattern: secretMatch },
            });
        }
        return this.routeToolInvocation(ctx, {
            decision: 'ALLOW',
            reason: 'Chat request permitted by AmazonQDeveloperIdeAdapter.',
        });
    }
    // ---------------------------------------------------------------------------
    // Hook: chatReceived
    // ---------------------------------------------------------------------------
    async _scanChatResponse(ctx) {
        const responseText = String(ctx.input['responseText'] ?? ctx.input['response'] ?? '');
        const secretMatch = this._scanForSecrets(responseText);
        if (secretMatch) {
            return this.routeToolInvocation(ctx, {
                decision: 'DENY',
                reason: `Chat response blocked: secret pattern '${secretMatch}' in response.`,
                metadata: { secretPattern: secretMatch },
            });
        }
        return this.routeToolInvocation(ctx, {
            decision: 'ALLOW',
            reason: 'Chat response passed Amazon Q ingress scan.',
        });
    }
    // ---------------------------------------------------------------------------
    // Hook: suggestionAccepted
    // ---------------------------------------------------------------------------
    async _auditSuggestionAccepted(ctx) {
        const targetFilePath = String(ctx.input['targetFilePath'] ?? '');
        const completionId = String(ctx.input['completionId'] ?? '');
        this.emit(buildIdeAuditEvent('ide:tool-invocation-approved', {
            ideId: this.ideId,
            adapterId: this.adapterId,
            sessionId: ctx.sessionHandle.sessionId,
            initiatingUserId: ctx.initiatingUser.userId,
            tool: ctx.tool,
            detail: `Developer accepted Amazon Q suggestion. Target: ${targetFilePath}. CompletionId: ${completionId || 'n/a'}.`,
            data: { targetFilePath, completionId },
        }));
        return this.routeToolInvocation(ctx, {
            decision: 'ALLOW',
            reason: `Suggestion acceptance audited for '${targetFilePath}'.`,
        });
    }
    // ---------------------------------------------------------------------------
    // Hook: suggestionRejected
    // ---------------------------------------------------------------------------
    async _auditSuggestionRejected(ctx) {
        const reason = String(ctx.input['reason'] ?? 'not-specified');
        const completionId = String(ctx.input['completionId'] ?? '');
        this.emit(buildIdeAuditEvent('ide:tool-invocation-approved', {
            ideId: this.ideId,
            adapterId: this.adapterId,
            sessionId: ctx.sessionHandle.sessionId,
            initiatingUserId: ctx.initiatingUser.userId,
            tool: ctx.tool,
            detail: `Developer rejected Amazon Q suggestion. Reason: ${reason}. CompletionId: ${completionId || 'n/a'}.`,
        }));
        return this.routeToolInvocation(ctx, {
            decision: 'ALLOW',
            reason: `Suggestion rejection audited. Reason: ${reason}.`,
        });
    }
    // ---------------------------------------------------------------------------
    // Amazon Q-specific Hook: awsResourceOperationRequested (PT-ADAPT-AMAZONQ-3)
    //
    // Amazon Q Developer's "agent for AWS" can create/modify/delete AWS resources.
    // Destructive operations require explicit approval; all resource operations
    // are audited with resource provenance.
    // ---------------------------------------------------------------------------
    async awsResourceOperationRequested(ctx) {
        this.ensureInitialized();
        const { resourceType, operation, resourceArn, region } = ctx;
        const effectiveRegion = region ?? this.aqConfig?.awsRegion ?? 'us-east-1';
        // 1. BAA region check
        if (this._isHipaaOrPciBinding() && !AMAZON_Q_BAA_REGIONS.includes(effectiveRegion)) {
            const decision = {
                decision: 'DENY',
                reason: `AWS resource operation blocked: region '${effectiveRegion}' is not on the ` +
                    `BAA-eligible list for pack binding '${this.config?.packId}'. ` +
                    `Permitted regions: ${AMAZON_Q_BAA_REGIONS.join(', ')}.`,
                metadata: { region: effectiveRegion, operation, resourceType },
            };
            this.emit(buildIdeAuditEvent('ide:tool-invocation-denied', {
                ideId: this.ideId,
                adapterId: this.adapterId,
                tool: 'aq:aws-resource-operation',
                detail: decision.reason,
                data: { region: effectiveRegion, resourceType, operation },
            }));
            return decision;
        }
        // 2. Destructive operation gate -- requires explicit approval
        if (DESTRUCTIVE_AWS_OPERATIONS.has(operation)) {
            const tier = this.aqConfig?.destructiveOperationReviewerTier ?? 'T3_SECURITY';
            const decision = {
                decision: 'REQUIRE_APPROVAL',
                reason: `AWS destructive operation '${operation}' on '${resourceType}' ` +
                    `(${resourceArn ?? 'ARN unknown'}) requires explicit approval. ` +
                    `This operation cannot be reversed without a recovery procedure. ` +
                    `Reviewer tier: ${tier}.`,
                metadata: {
                    resourceType,
                    operation,
                    resourceArn,
                    region: effectiveRegion,
                    destructive: true,
                    tier,
                },
            };
            this.emit(buildIdeAuditEvent('ide:tool-invocation-require-approval', {
                ideId: this.ideId,
                adapterId: this.adapterId,
                tool: 'aq:aws-resource-operation',
                detail: decision.reason,
                data: { resourceType, operation, resourceArn, region: effectiveRegion },
            }));
            return decision;
        }
        // 3. Non-destructive operation -- audit and allow
        this.emit(buildIdeAuditEvent('ide:tool-invocation-approved', {
            ideId: this.ideId,
            adapterId: this.adapterId,
            tool: 'aq:aws-resource-operation',
            detail: `AWS resource operation '${operation}' on '${resourceType}' (${resourceArn ?? 'unknown'}) in ${effectiveRegion} permitted.`,
            data: { resourceType, operation, resourceArn, region: effectiveRegion },
        }));
        return {
            decision: 'ALLOW',
            reason: `AWS resource operation '${operation}' on '${resourceType}' permitted.`,
            metadata: { resourceType, operation, resourceArn, region: effectiveRegion },
        };
    }
    // ---------------------------------------------------------------------------
    // Amazon Q-specific Hook: iamPolicyGenerationRequested (PT-ADAPT-AMAZONQ-2)
    //
    // Q Developer writes IAM policies. This gate runs a policy-safety
    // classifier and routes unsafe policies to a named reviewer.
    // ---------------------------------------------------------------------------
    async iamPolicyGenerationRequested(ctx) {
        this.ensureInitialized();
        const { roleName, intent, policyDocument } = ctx;
        // Classify the policy document if provided (post-generation gate)
        if (policyDocument) {
            const findings = this._classifyIamPolicy(policyDocument);
            if (findings.length > 0) {
                const tier = this.aqConfig?.iamReviewerTier ?? 'T3_SECURITY';
                const isRegulated = this._isHipaaOrPciBinding();
                if (isRegulated) {
                    // Under PCI or HIPAA, overly-broad IAM policies must be reviewed
                    const decision = {
                        decision: 'REQUIRE_APPROVAL',
                        reason: `IAM policy generation for role '${roleName}' flagged under ` +
                            `'${this.config?.packId}' binding. ` +
                            `Policy safety findings: [${findings.join(', ')}]. ` +
                            `Overly-broad IAM policies are a PCI DSS Requirement 7 and HIPAA access-control violation. ` +
                            `Reviewer tier: ${tier}.`,
                        metadata: { roleName, intent, iamFindings: findings, tier },
                    };
                    this.emit(buildIdeAuditEvent('ide:tool-invocation-require-approval', {
                        ideId: this.ideId,
                        adapterId: this.adapterId,
                        tool: 'aq:iam-policy-generation',
                        detail: decision.reason,
                        data: { roleName, iamFindings: findings },
                    }));
                    return decision;
                }
                // Non-regulated pack: allow with warn audit
                this.emit(buildIdeAuditEvent('ide:tool-invocation-approved', {
                    ideId: this.ideId,
                    adapterId: this.adapterId,
                    tool: 'aq:iam-policy-generation',
                    detail: `IAM policy for '${roleName}' has safety findings [${findings.join(', ')}] but no regulated pack binding. Allowed with WARN.`,
                    data: { roleName, iamFindings: findings },
                }));
                return {
                    decision: 'ALLOW',
                    reason: `IAM policy permitted with findings: [${findings.join(', ')}]. Consider adding a PCI or HIPAA pack binding to enforce policy review.`,
                    metadata: { roleName, iamFindings: findings },
                };
            }
        }
        // Clean policy or no policy document provided for pre-generation gate
        this.emit(buildIdeAuditEvent('ide:tool-invocation-approved', {
            ideId: this.ideId,
            adapterId: this.adapterId,
            tool: 'aq:iam-policy-generation',
            detail: `IAM policy generation for role '${roleName}' (intent: ${intent}) permitted.`,
            data: { roleName, intent },
        }));
        return {
            decision: 'ALLOW',
            reason: `IAM policy generation for '${roleName}' permitted. DataClass: infrastructure-change.`,
            metadata: { roleName, intent, dataClass: 'infrastructure-change' },
        };
    }
    // ---------------------------------------------------------------------------
    // Amazon Q-specific Hook: codeTransformRequested
    //
    // Q Developer whole-project Java modernization. Audit chain needs project-
    // level provenance: projectName + targetVersion.
    // ---------------------------------------------------------------------------
    async codeTransformRequested(ctx) {
        this.ensureInitialized();
        const { projectName, targetVersion, language, estimatedFilesCount } = ctx;
        // BAA region check for bulk operations under regulated packs
        const region = this.aqConfig?.awsRegion ?? 'us-east-1';
        if (this._isHipaaOrPciBinding() && !AMAZON_Q_BAA_REGIONS.includes(region)) {
            return {
                decision: 'DENY',
                reason: `Code Transform blocked: region '${region}' is not BAA-eligible for ` +
                    `'${this.config?.packId}' pack binding. ` +
                    `Code Transform is a bulk operation that processes all source files.`,
                metadata: { region, projectName, targetVersion },
            };
        }
        this.emit(buildIdeAuditEvent('ide:tool-invocation-approved', {
            ideId: this.ideId,
            adapterId: this.adapterId,
            tool: 'aq:code-transform-requested',
            detail: `Code Transform initiated. Project: ${projectName}. ` +
                `Target: ${targetVersion}. Language: ${language ?? 'java'}. ` +
                `Files: ${estimatedFilesCount ?? 'unknown'}.`,
            data: { projectName, targetVersion, language, estimatedFilesCount, region },
        }));
        return {
            decision: 'ALLOW',
            reason: `Code Transform permitted for project '${projectName}' -> ${targetVersion}. ` +
                `Audit provenance recorded.`,
            metadata: {
                projectName,
                targetVersion,
                language: language ?? 'java',
                estimatedFilesCount,
                region,
                dataClass: 'bulk-code-transform',
            },
        };
    }
    // ---------------------------------------------------------------------------
    // IdeAdapter: interceptToolInvocation dispatch for Amazon Q-specific surfaces
    // ---------------------------------------------------------------------------
    async _gateAwsResourceOperation(ctx) {
        return this.awsResourceOperationRequested({
            resourceType: String(ctx.input['resourceType'] ?? 'unknown'),
            operation: String(ctx.input['operation'] ?? ''),
            resourceArn: ctx.input['resourceArn'],
            region: ctx.input['region'],
            sessionId: ctx.sessionHandle.sessionId,
        });
    }
    async _gateIamPolicyGeneration(ctx) {
        return this.iamPolicyGenerationRequested({
            roleName: String(ctx.input['roleName'] ?? ctx.input['role'] ?? 'unknown-role'),
            intent: String(ctx.input['intent'] ?? ''),
            policyDocument: ctx.input['policyDocument'],
            sessionId: ctx.sessionHandle.sessionId,
        });
    }
    async _gateCodeTransform(ctx) {
        return this.codeTransformRequested({
            projectName: String(ctx.input['projectName'] ?? 'unknown-project'),
            targetVersion: String(ctx.input['targetVersion'] ?? ''),
            language: ctx.input['language'],
            estimatedFilesCount: ctx.input['estimatedFilesCount'],
            sessionId: ctx.sessionHandle.sessionId,
        });
    }
    // ---------------------------------------------------------------------------
    // Capabilities
    // ---------------------------------------------------------------------------
    getIdeCapabilities() {
        return {
            runtimeHooks: true,
            prBoundary: false,
            userIdentity: true,
            reviewerRouting: true,
            integrationMode: 'amazon-q-normalised-event-shim',
        };
    }
    // ---------------------------------------------------------------------------
    // Error translation
    // ---------------------------------------------------------------------------
    translateError(raw) {
        if (raw instanceof IdeAttributionError)
            return raw;
        if (raw instanceof IdeUnsupportedError)
            return raw;
        return super.translateError(raw);
    }
    // ---------------------------------------------------------------------------
    // Helpers
    // ---------------------------------------------------------------------------
    _scanForSecrets(text) {
        if (!text)
            return null;
        for (const { name, re } of AQ_SECRET_PATTERNS) {
            if (re.test(text))
                return name;
        }
        return null;
    }
    _scanForPhiIndicators(text) {
        if (!text)
            return null;
        for (const re of AQ_PHI_INDICATORS) {
            if (re.test(text))
                return re.source;
        }
        return null;
    }
    _isHipaaOrPciBinding() {
        const packId = this.config?.packId ?? '';
        return packId === 'hipaa' || packId.startsWith('hipaa') || packId === 'pci-dss' || packId.startsWith('pci');
    }
    /**
     * Classify an IAM policy document string for unsafe patterns.
     * Returns array of finding names. Empty = safe.
     */
    _classifyIamPolicy(policyDocument) {
        const findings = [];
        for (const { name, re } of IAM_UNSAFE_PATTERNS) {
            if (re.test(policyDocument)) {
                findings.push(name);
            }
        }
        return findings;
    }
    /**
     * Check BAA region compliance. Returns a DENY decision if the configured
     * region is not BAA-eligible under a regulated pack binding, or null.
     * (PT-ADAPT-AMAZONQ-1)
     */
    _checkBaaRegion(ctx) {
        if (!this._isHipaaOrPciBinding())
            return null;
        const region = this.aqConfig?.awsRegion ?? 'us-east-1';
        if (!AMAZON_Q_BAA_REGIONS.includes(region)) {
            return {
                decision: 'DENY',
                reason: `Amazon Q Developer request blocked: region '${region}' is not on the ` +
                    `BAA-eligible list for pack binding '${this.config?.packId}'. ` +
                    `Permitted BAA regions: ${AMAZON_Q_BAA_REGIONS.join(', ')}.`,
                metadata: {
                    region,
                    packId: this.config?.packId,
                    baaRegions: AMAZON_Q_BAA_REGIONS,
                },
            };
        }
        return null;
    }
    /** Expose the configured AWS region for diagnostics / tests. */
    getAwsRegion() {
        return this.aqConfig?.awsRegion ?? 'us-east-1';
    }
}
//# sourceMappingURL=amazon-q-developer.js.map