// tools/create-spec-hu.ts — HU.md content generation for create-spec
// SPEC-010: adds Quality Guidelines, Testing Strategy, and Impact Analysis sections.
// SPEC-027: adds NFR section, tech-debt type, multi-tenancy criteria.
// SPEC-036: requestDocs parameter — include context request block before criteria.
// SPEC-048: adds Platform Engineering sections (DORA, golden path, portal, onboarding).
// SPEC-025 tech debt: adds Dependency Warnings section when pre-spec dep check finds issues.
import { detectMissingAreas, buildRequestPrompt } from '../engine/context-merger.js';
import { addSecuritySection } from './create-spec/security-spec-adapter.js';
import { buildPrivacyHuSection } from './create-spec/privacy-spec-adapter.js';
import { buildEventHuSection } from './create-spec/event-spec-adapter.js';
import { deriveNFRProfile, generateNFRSection } from '../engine/nfr-profile-detector.js';
import { generateQualityGuidelines, generateTestingStrategy, generateImpactAnalysis, generateMultiTenancyCriteria, } from './create-spec-hu/quality-helpers.js';
import { getDoraCriteria, getDeveloperPortalCriteria, getOnboardingCriteria, } from '../engine/platform-engineering/dora-advisor.js';
import { getGoldenPathCriteria, getSelfServiceCriteria, } from '../engine/platform-engineering/golden-path-generator.js';
import { buildOtelHuSection } from './create-spec-hu/otel-hu-adapter.js';
import { buildSupplyChainHuSection } from './create-spec-hu/supply-chain-hu-adapter.js';
import { buildLlmSecurityHuSection } from './create-spec-hu/llm-security-hu-adapter.js';
import { buildLocalFirstHuSection } from './create-spec-hu/local-first-hu-adapter.js';
import { buildAdvancedTestingHuSection } from './create-spec-hu/advanced-testing-hu-adapter.js';
import { buildSwiftAndroidHuSection } from './create-spec-hu/swift-android-hu-adapter.js';
import { buildAiTestingGovernanceSection } from './create-spec-hu/ai-testing-governance-adapter.js';
import { buildBuildToolHuSection } from './create-spec-hu/build-tool-hu-adapter.js';
import { buildAiNativeHuSection } from './create-spec-hu/ai-native-hu-adapter.js';
import { buildFrontendPerfHuSection } from './create-spec-hu/frontend-perf-hu-adapter.js';
import { generateHUBody, buildLintingRulesSection, buildEnvVariablesSection, } from './create-spec-hu/hu-body-generators.js';
export { generateHUBody, generateIosAccessibilityCriteria, generateAndroidAccessibilityCriteria, } from './create-spec-hu/hu-body-generators.js';
// Keywords that trigger the Linting Rules section
const LINTING_KEYWORDS = ['lint', 'format', 'style', 'eslint', 'prettier', 'code quality'];
// Keywords that trigger the Environment Variables section
const ENV_KEYWORDS = [
    'env',
    'environment',
    'api key',
    'apikey',
    'secret',
    'token',
    'config',
    'credential',
];
// Production targets that warrant NFR sections
const PRODUCTION_TARGETS = new Set(['backend', 'fullstack', 'shared']);
/**
 * Generate HU.md (User Story) content adapted by spec type.
 * SPEC-010: includes Quality Guidelines, Testing Strategy, and Impact Analysis.
 * SPEC-027: includes NFR section for production features, tech-debt format,
 *           and multi-tenancy isolation criteria when project is multi-tenant.
 * SPEC-036: requestDocs=true appends a context-request block for PRD/wireframes.
 * SPEC-048: teamScale triggers platform engineering sections (DORA, golden path, portal).
 * SPEC-025 tech debt: depWarnings adds a dependency warning section when issues are found.
 */
export function generateHUContent(spec, description, knowledge, requestDocs, teamScale, depWarnings) {
    const tagsYaml = spec.tags.length > 0 ? `[${spec.tags.join(', ')}]` : '[]';
    const createdDate = spec.createdAt.split('T')[0] ?? spec.createdAt;
    const header = [
        '---',
        `id: ${spec.id}`,
        `title: "${spec.title.replace(/"/g, '\\"')}"`,
        `type: ${spec.type}`,
        `scope: ${spec.scope}`,
        `target: ${spec.target}`,
        `status: ${spec.status}`,
        `difficulty: ${spec.difficulty}`,
        `risk: ${spec.risk}`,
        `tags: ${tagsYaml}`,
        `parent: ${spec.feature ?? 'null'}`,
        `created: ${createdDate}`,
        '---',
        '',
        `# ${spec.id}: ${spec.title}`,
        '',
    ];
    const body = generateHUBody(spec.type, description, spec.target, knowledge);
    const qualityGuidelines = generateQualityGuidelines(spec, knowledge);
    const testingStrategy = generateTestingStrategy(spec);
    const impactAnalysis = generateImpactAnalysis(spec);
    const securitySection = addSecuritySection(spec, description, knowledge);
    // SPEC-030: Privacy section — auto-generated when spec involves PII
    const privacySection = buildPrivacyHuSection(spec, description, knowledge);
    // SPEC-031: Event-driven section — auto-generated when project uses a known broker
    const eventSection = knowledge ? buildEventHuSection(spec.title, knowledge) : '';
    // SPEC-027: NFR section for production backend/fullstack features
    const nfrSection = spec.type === 'feature' && PRODUCTION_TARGETS.has(spec.target)
        ? generateNFRSection(deriveNFRProfile(knowledge?.stack ?? []))
        : [];
    // SPEC-027: multi-tenancy isolation criteria when project is multi-tenant
    const multiTenancySection = knowledge !== null && knowledge !== undefined ? generateMultiTenancyCriteria(knowledge) : [];
    // SPEC-025 tech-debt: conditional linting and env sections
    const searchText = `${spec.title} ${description} ${spec.tags.join(' ')}`.toLowerCase();
    const lintingSection = LINTING_KEYWORDS.some((kw) => searchText.includes(kw))
        ? buildLintingRulesSection()
        : [];
    const envVarsSection = ENV_KEYWORDS.some((kw) => searchText.includes(kw))
        ? buildEnvVariablesSection()
        : [];
    // SPEC-048: Platform engineering sections for multi-team or platform-engineering-candidate
    const resolvedTeamScale = teamScale ?? 'solo';
    const doraSection = getDoraCriteria(resolvedTeamScale);
    const goldenPathSection = spec.type === 'feature' ? getGoldenPathCriteria() : [];
    const selfServiceSection = spec.type === 'feature' ? getSelfServiceCriteria() : [];
    const developerPortalSection = getDeveloperPortalCriteria(resolvedTeamScale);
    const onboardingSection = getOnboardingCriteria(resolvedTeamScale);
    const footer = [
        '',
        '## Dependencies',
        '',
        spec.dependencies.length > 0 ? spec.dependencies.map((d) => `- ${d}`).join('\n') : '- None',
        '',
        '## Tags',
        '',
        spec.tags.map((tag) => `\`${tag}\``).join(', ') || 'None',
        '',
    ];
    // SPEC-036: requestDocs block — ask for PRD / wireframe before criteria generation
    const requestDocsSection = requestDocs && knowledge ? buildRequestDocsSection(knowledge) : [];
    // SPEC-025 tech debt: dep warnings block — surfaced when pre-spec check finds issues
    const depWarningsSection = buildDepWarningsSection(depWarnings);
    // SPEC-044: OTel criteria for microservice/distributed projects
    const otelSection = buildOtelHuSection(spec.type, spec.target, knowledge);
    // SPEC-046: Supply chain criteria for backend/fullstack specs with distribution
    const supplyChainSection = buildSupplyChainHuSection(spec.target, knowledge);
    // SPEC-045: LLM security criteria when LLM integration is detected
    const llmSecuritySection = buildLlmSecurityHuSection(knowledge);
    // SPEC-047: Local-first criteria when CRDT/sync signals detected
    const localFirstSection = buildLocalFirstHuSection(knowledge);
    // SPEC-049: Advanced testing criteria (PBT invariants, mutation score, a11y, test data)
    const advancedTestingSection = buildAdvancedTestingHuSection(spec.target, knowledge);
    // SPEC-013 TD-P14-03: Swift on Android experimental notice
    const swiftAndroidSection = buildSwiftAndroidHuSection(spec, knowledge);
    // SPEC-049 TD-P14-02: AI testing governance (test lifecycle ownership)
    const aiTestingGovernanceSection = buildAiTestingGovernanceSection(knowledge);
    // SPEC-050 S5: Build-tool-aware criteria (C12: rolldown tree-shaking, C13: turbopack HMR)
    const buildToolHuSection = buildBuildToolHuSection(knowledge);
    // SPEC-056: AI-native architecture criteria (latency, fallback, prompt versioning, cost)
    const aiNativeSection = buildAiNativeHuSection(knowledge);
    // SPEC-057: Frontend perf criteria (Core Web Vitals, bundle size, MFE boundaries, SSR hydration)
    const frontendPerfHuSection = buildFrontendPerfHuSection(knowledge);
    return [
        ...header,
        ...depWarningsSection,
        ...body,
        ...qualityGuidelines,
        ...testingStrategy,
        ...impactAnalysis,
        ...securitySection,
        ...privacySection,
        eventSection,
        ...nfrSection,
        ...multiTenancySection,
        ...otelSection,
        ...supplyChainSection,
        ...llmSecuritySection,
        ...localFirstSection,
        ...advancedTestingSection,
        ...swiftAndroidSection,
        ...aiTestingGovernanceSection,
        ...buildToolHuSection,
        ...aiNativeSection,
        ...frontendPerfHuSection,
        ...doraSection,
        ...goldenPathSection,
        ...selfServiceSection,
        ...developerPortalSection,
        ...onboardingSection,
        ...lintingSection,
        ...envVarsSection,
        ...requestDocsSection,
        ...footer,
    ].join('\n');
}
// ---------------------------------------------------------------------------
// SPEC-025 tech debt: dep warnings helper
// ---------------------------------------------------------------------------
function buildDepWarningsSection(depWarnings) {
    if (!depWarnings?.hasWarnings) {
        return [];
    }
    const lines = [
        '',
        '## Dependency Warnings',
        '',
        '> The following dependency issues were detected in this project. Address them before proceeding.',
        '',
    ];
    for (const line of depWarnings.warningLines) {
        lines.push(line);
    }
    lines.push('');
    return lines;
}
// ---------------------------------------------------------------------------
// SPEC-036: requestDocs helper
// ---------------------------------------------------------------------------
function buildRequestDocsSection(knowledge) {
    const missingAreas = detectMissingAreas(knowledge);
    if (missingAreas.length === 0) {
        return [];
    }
    const prompt = buildRequestPrompt(missingAreas, knowledge);
    return [
        '',
        '## Documentacion Recomendada',
        '',
        prompt,
        '',
        'Compartí el PRD o wireframe para que pueda generar criterios más precisos.',
        '',
    ];
}
//# sourceMappingURL=create-spec-hu.js.map