// tools/data-governance/detect-handler.ts — detect and retention-policy subcommands
import { specStore, knowledgeStore } from '../../storage/index.js';
import { ti } from '../../i18n/index.js';
import { detectPIIInSpec, detectLegalFramework, generateRetentionPolicy, generatePrivacySection, } from '../../engine/pii-detector.js';
import { readFile } from 'node:fs/promises';
// ---------------------------------------------------------------------------
// detect subcommand
// ---------------------------------------------------------------------------
export async function handleDetect(specId, projectId, inlineContent, projectPath) {
    // Build title and criteria from specId or inline content
    if (!specId && !inlineContent) {
        return {
            content: [
                {
                    type: 'text',
                    text: ti('errors.invalidInput', {
                        details: 'Either specId or specContent must be provided for the detect subcommand',
                    }),
                },
            ],
            isError: true,
        };
    }
    let title;
    let criteria;
    if (specId) {
        const spec = await specStore.getSpec(projectId, specId);
        if (!spec) {
            return {
                content: [{ type: 'text', text: ti('spec.notFound', { id: specId }) }],
                isError: true,
            };
        }
        title = spec.title;
        criteria = '';
        if (spec.specPath) {
            try {
                criteria = await readFile(spec.specPath, 'utf-8');
            }
            catch {
                /* file not available */
            }
        }
    }
    else {
        // inlineContent is guaranteed non-empty here due to the early guard above
        const content = inlineContent ?? '';
        const parts = content.split('\n');
        title = parts[0] ?? '';
        criteria = content;
    }
    const result = detectPIIInSpec(title, criteria, criteria);
    const framework = detectLegalFramework({ projectPath, existingText: criteria });
    const retentionPolicy = generateRetentionPolicy(result.fields, framework);
    const privacySection = generatePrivacySection(result, framework, retentionPolicy);
    const requirement = {
        specId: specId ?? 'inline',
        detectedAt: new Date().toISOString(),
        piiFields: result.fields,
        legalBasis: result.recommendedLegalBasis,
        retentionPolicy,
        consentRequired: result.requiresConsentFlow,
        consentGranular: result.requiresConsentFlow,
        auditTrailRequired: result.requiresAuditTrail,
        auditRetentionDays: 365,
        privacyNoticeSection: privacySection.join('\n'),
        challengeRequired: result.hasPII,
        challengeCompleted: false,
    };
    return {
        content: [
            {
                type: 'text',
                text: ti('tools.data_governance.detectSuccess', {
                    count: String(result.fields.length),
                    hasPII: String(result.hasPII),
                }),
            },
            {
                type: 'text',
                text: JSON.stringify({
                    subcommand: 'detect',
                    detectionResult: result,
                    framework,
                    retentionPolicy,
                    requirement,
                    privacySection: privacySection.join('\n'),
                }, null, 2),
            },
        ],
    };
}
// ---------------------------------------------------------------------------
// retention-policy subcommand
// ---------------------------------------------------------------------------
export function handleRetentionPolicy(modelName, projectPath) {
    // When no model name, generate a default policy for a generic user model
    const effectiveModel = modelName ?? 'User';
    // Detect framework from project path context
    const framework = detectLegalFramework({ projectPath });
    const defaultRetentionPolicy = generateRetentionPolicy([
        {
            fieldName: 'example',
            modelContext: effectiveModel,
            category: 'personal',
            isSensitiveSpecial: false,
            canBeAnonymized: true,
            canBePseudonymized: true,
        },
    ], framework);
    return {
        content: [
            {
                type: 'text',
                text: ti('tools.data_governance.retentionSuccess', { model: effectiveModel }),
            },
            {
                type: 'text',
                text: JSON.stringify({
                    subcommand: 'retention-policy',
                    modelName: effectiveModel,
                    framework,
                    retentionPolicy: defaultRetentionPolicy,
                    auditFields: [
                        'created_at',
                        'updated_at',
                        'deleted_at',
                        'data_owner_id',
                        'retention_expires_at',
                    ],
                }, null, 2),
            },
        ],
    };
}
// Re-export for use by the main handler
export { knowledgeStore };
//# sourceMappingURL=detect-handler.js.map