// tools/create-spec/analytics-spec-adapter.ts
// SPEC-032: Generates analytics spec sections for features with user interaction.
import { isUserInteractionFeature, isFunnelFeature, isABTestFeature, generateEvents, generateFunnelEvents, hasPIIProperties, } from '../../engine/analytics-detector.js';
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
 * Returns true when create_spec should generate an Analytics section.
 * Requires: user interaction feature AND a detected analytics provider.
 */
export function shouldGenerateAnalyticsSection(title, description, criteria, stack) {
    if (!stack || stack.provider === 'unknown') {
        return false;
    }
    return isUserInteractionFeature(title, description, criteria);
}
/**
 * Builds a complete AnalyticsSpec for a feature.
 * Called from create_spec when shouldGenerateAnalyticsSection returns true.
 */
export function buildAnalyticsSpec(specId, title, description, criteria, stack, hasGdprOrCcpa) {
    const events = generateEvents(description, stack);
    // Add consent flag if GDPR/CCPA is active
    if (hasGdprOrCcpa) {
        for (const event of events) {
            event.consentRequired = true;
        }
    }
    const funnels = isFunnelFeature(title, description, criteria)
        ? [generateFunnelEvents(description, stack)]
        : [];
    const experiments = isABTestFeature(title, description, criteria)
        ? [buildDefaultABTest(title)]
        : [];
    return {
        provider: stack.provider,
        integrationMethod: stack.integrationMethod,
        namingConvention: stack.namingConvention,
        events,
        funnels,
        experiments,
        specId,
    };
}
/**
 * Generates a "no provider detected" note for specs where analytics is not configured.
 */
export function buildNoProviderNote() {
    return ('\n> **Nota:** No se detecto proveedor de analytics configurado. ' +
        'Para habilitar la especificacion automatica de eventos, considera integrar uno de los ' +
        'proveedores soportados (PostHog, Mixpanel, Amplitude, Segment, GA4).\n');
}
/**
 * Generates the HU.md Analytics section as a Markdown string.
 */
export function buildAnalyticsHuSection(analyticsSpec) {
    const lines = ['', '## Analytics', ''];
    lines.push(`**Provider:** ${analyticsSpec.provider}`);
    lines.push(`**Integration:** ${analyticsSpec.integrationMethod}`);
    lines.push(`**Naming convention:** ${analyticsSpec.namingConvention}`);
    lines.push('');
    if (analyticsSpec.events.length > 0) {
        lines.push('### Events to Track');
        lines.push('');
        for (const event of analyticsSpec.events) {
            lines.push(`#### \`${event.name}\``);
            lines.push(`- **Trigger:** ${event.trigger}`);
            lines.push(`- **Business goal:** ${event.businessGoal}`);
            if (event.consentRequired) {
                lines.push('- **Consent required:** Yes (GDPR/CCPA)');
            }
            if (event.includesPII) {
                lines.push('- **PII detected:** Yes — anonymization required');
            }
            lines.push('- **Properties:**');
            for (const prop of event.properties) {
                const required = prop.required ? 'required' : 'optional';
                lines.push(`  - \`${prop.name}\` (${prop.type}, ${required}): ${prop.description}`);
            }
            lines.push('');
        }
    }
    if (analyticsSpec.funnels.length > 0) {
        lines.push('### Funnels');
        lines.push('');
        for (const funnel of analyticsSpec.funnels) {
            lines.push(`#### ${funnel.name}`);
            lines.push(`- **Conversion goal:** ${funnel.conversionGoal}`);
            lines.push(`- **Steps:** ${funnel.steps.length}`);
            for (let i = 0; i < funnel.steps.length; i++) {
                const step = funnel.steps[i];
                if (step) {
                    lines.push(`  - Step ${i + 1}: \`${step.name}\``);
                }
            }
            lines.push('');
        }
    }
    if (analyticsSpec.experiments.length > 0) {
        lines.push('### A/B Experiments');
        lines.push('');
        for (const exp of analyticsSpec.experiments) {
            lines.push(`#### ${exp.name}`);
            lines.push(`- **Hypothesis:** ${exp.hypothesis}`);
            lines.push(`- **Variants:** ${exp.variants.join(', ')}`);
            lines.push(`- **Primary metric:** ${exp.primaryMetric}`);
            lines.push(`- **Guard metrics:** ${exp.guardMetrics.join(', ')}`);
            lines.push(`- **Guard threshold:** ${(exp.guardThreshold * 100).toFixed(0)}% relative degradation`);
            lines.push(`- **Sample size / variant:** ${exp.estimatedSampleSize}`);
            lines.push(`- **Estimated duration:** ${exp.estimatedDuration}`);
            lines.push('');
        }
    }
    lines.push('### Analytics Acceptance Criteria');
    lines.push('');
    for (const event of analyticsSpec.events) {
        lines.push(`- [ ] Event \`${event.name}\` is implemented and fires with all required properties`);
        if (event.consentRequired) {
            lines.push(`- [ ] Event \`${event.name}\` only fires after analytics consent is granted`);
        }
    }
    // PII anonymization criterion
    const piiEvents = analyticsSpec.events.filter((e) => e.includesPII || hasPIIProperties(e.properties));
    if (piiEvents.length > 0) {
        lines.push('- [ ] All event properties with PII are anonymized: use hashed `user_id`, ' +
            'truncated IP (first 3 octets), exclude name/email from event properties directly');
    }
    lines.push('');
    return lines.join('\n');
}
/**
 * Builds a default A/B test for a feature.
 */
function buildDefaultABTest(title) {
    const slug = title
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .slice(0, 40);
    return {
        name: `${slug}-experiment`,
        hypothesis: `If we change the ${title}, then conversion will improve because users will find it more intuitive`,
        variants: ['control', 'variant_a'],
        primaryMetric: 'conversion_rate',
        guardMetrics: ['bounce_rate', 'error_rate'],
        estimatedSampleSize: 1000,
        estimatedDuration: '14 days',
        guardThreshold: 0.05,
        provider: undefined,
    };
}
// ---------------------------------------------------------------------------
// Re-export detection helpers for use in create-spec.ts
// ---------------------------------------------------------------------------
export { isUserInteractionFeature, hasPIIProperties } from '../../engine/analytics-detector.js';
//# sourceMappingURL=analytics-spec-adapter.js.map