import { Document, Packer, Paragraph, TextRun, HeadingLevel, Table, TableRow, TableCell, WidthType, TableLayoutType } from 'docx';

// Google Docs and macOS viewers render docx tables reliably only when
// explicit DXA column widths are provided with fixed table layout.
const TABLE_WIDTH_40 = 3855;
const TABLE_WIDTH_60 = 5783;

function createCompatibleTable(rows: TableRow[], columnWidths: number[]): Table {
  return new Table({
    rows,
    columnWidths,
    width: { size: 0, type: WidthType.AUTO },
    layout: TableLayoutType.FIXED,
    alignment: 'left',
  });
}

export interface ComplianceReportData {
  project: {
    name: string;
    id: string;
    repository: string;
  };
  client: {
    name: string;
  };
  migration: {
    source_language: string;
    target_language: string;
    job_id: string;
    date: string;
  };
  report: {
    date: string;
    version: string;
    classification: string;
  };
  scriba: {
    engine_version: string;
  };
  frameworks: {
    list: string;
  };
  summary: {
    scope_description: string;
    overall_posture: string;
  };
  metrics: {
    files_analyzed: string;
    files_analyzed_delta: string;
    files_analyzed_trend: string;
    loc_target: string;
    loc_target_delta: string;
    loc_target_trend: string;
    req_total: string;
    req_total_delta: string;
    req_total_trend: string;
    req_met: string;
    req_met_delta: string;
    req_met_trend: string;
    req_partial: string;
    req_partial_delta: string;
    req_partial_trend: string;
    req_not_met: string;
    req_not_met_delta: string;
    req_not_met_trend: string;
    req_na: string;
    req_na_delta: string;
    req_na_trend: string;
    findings_critical: string;
    findings_critical_delta: string;
    findings_critical_trend: string;
    findings_high: string;
    findings_high_delta: string;
    findings_high_trend: string;
    findings_medium: string;
    findings_medium_delta: string;
    findings_medium_trend: string;
    findings_low: string;
    findings_low_delta: string;
    findings_low_trend: string;
    compliance_score: string;
    compliance_score_delta: string;
    compliance_score_trend: string;
  };
  recommendations: string[];
  source: {
    language_runtime: string;
    frameworks: string;
  };
  target: {
    language_runtime: string;
    frameworks: string;
  };
  migration_approach: string;
  deltas: Array<{
    area: string;
    change_description: string;
    compliance_impact: string;
    frameworks_affected: string;
  }>;
  methodology: {
    engines: string;
    rulesource: string[];
    limitations: string;
  };
  applicability: {
    gdpr: { in_scope: string; rationale: string; profile: string };
    sox: { in_scope: string; rationale: string; profile: string };
    pci: { in_scope: string; rationale: string; profile: string };
    hipaa: { in_scope: string; rationale: string; profile: string };
    iso27001: { in_scope: string; rationale: string; profile: string };
  };
  gdpr: {
    summary: string;
    scorecard: {
      met: { count: string; pct: string; delta: string };
      partial: { count: string; pct: string; delta: string };
      not_met: { count: string; pct: string; delta: string };
      na: { count: string; pct: string; delta: string };
      score: { count: string; pct: string; delta: string };
    };
    requirements: Array<{
      id: string;
      description: string;
      control_evidence: string;
      status: string;
      code_locations: string;
    }>;
    findings: Array<{
      title: string;
      id: string;
      severity: string;
      requirement_ref: string;
      description: string;
      file: string;
      lines: string;
      symbol: string;
      code_snippet: string;
      source_snippet: string;
      recommendation: string;
      references: string;
    }>;
    specific_notes: string;
  };
  sox: {
    summary: string;
    scorecard: {
      met: { count: string; pct: string; delta: string };
      partial: { count: string; pct: string; delta: string };
      not_met: { count: string; pct: string; delta: string };
      na: { count: string; pct: string; delta: string };
      score: { count: string; pct: string; delta: string };
    };
    requirements: Array<{
      id: string;
      description: string;
      control_evidence: string;
      status: string;
      code_locations: string;
    }>;
    findings: Array<{
      title: string;
      id: string;
      severity: string;
      requirement_ref: string;
      description: string;
      file: string;
      lines: string;
      symbol: string;
      code_snippet: string;
      source_snippet: string;
      recommendation: string;
      references: string;
    }>;
    specific_notes: string;
  };
  pci: {
    summary: string;
    scorecard: {
      met: { count: string; pct: string; delta: string };
      partial: { count: string; pct: string; delta: string };
      not_met: { count: string; pct: string; delta: string };
      na: { count: string; pct: string; delta: string };
      score: { count: string; pct: string; delta: string };
    };
    requirements: Array<{
      id: string;
      description: string;
      control_evidence: string;
      status: string;
      code_locations: string;
    }>;
    findings: Array<{
      title: string;
      id: string;
      severity: string;
      requirement_ref: string;
      description: string;
      file: string;
      lines: string;
      symbol: string;
      code_snippet: string;
      source_snippet: string;
      recommendation: string;
      references: string;
    }>;
    specific_notes: string;
  };
  hipaa: {
    summary: string;
    scorecard: {
      met: { count: string; pct: string; delta: string };
      partial: { count: string; pct: string; delta: string };
      not_met: { count: string; pct: string; delta: string };
      na: { count: string; pct: string; delta: string };
      score: { count: string; pct: string; delta: string };
    };
    requirements: Array<{
      id: string;
      description: string;
      control_evidence: string;
      status: string;
      code_locations: string;
    }>;
    findings: Array<{
      title: string;
      id: string;
      severity: string;
      requirement_ref: string;
      description: string;
      file: string;
      lines: string;
      symbol: string;
      code_snippet: string;
      source_snippet: string;
      recommendation: string;
      references: string;
    }>;
    specific_notes: string;
  };
  iso27001: {
    summary: string;
    scorecard: {
      met: { count: string; pct: string; delta: string };
      partial: { count: string; pct: string; delta: string };
      not_met: { count: string; pct: string; delta: string };
      na: { count: string; pct: string; delta: string };
      score: { count: string; pct: string; delta: string };
    };
    requirements: Array<{
      id: string;
      description: string;
      control_evidence: string;
      status: string;
      code_locations: string;
    }>;
    findings: Array<{
      title: string;
      id: string;
      severity: string;
      requirement_ref: string;
      description: string;
      file: string;
      lines: string;
      symbol: string;
      code_snippet: string;
      source_snippet: string;
      recommendation: string;
      references: string;
    }>;
    specific_notes: string;
  };
  xmatrix: Array<{
    domain: string;
    gdpr: string;
    sox: string;
    pci: string;
    hipaa: string;
    iso27001: string;
  }>;
  remediation: Array<{
    title: string;
    id: string;
    priority: string;
    effort: string;
    findings_refs: string;
    frameworks: string;
    description: string;
    owner: string;
  }>;
  files: Array<{
    path: string;
    loc: string;
    findings_count: string;
    max_severity: string;
  }>;
  rules: Array<{
    id: string;
    title: string;
    pack: string;
    version: string;
    frameworks: string;
  }>;
}

export async function generateComplianceReportWord(data: ComplianceReportData): Promise<Buffer> {
  const doc = new Document({
    styles: {
      default: {
        document: {
          run: {
            font: 'Arial',
            size: 20,
            color: '222222',
          },
        },
      },
      paragraphStyles: [
        {
          id: 'Normal',
          name: 'Normal',
          run: {
            font: 'Arial',
            size: 20,
            color: '222222',
          },
          paragraph: {
            spacing: { line: 276, after: 120 },
          },
        },
        {
          id: 'Heading1',
          name: 'Heading 1',
          basedOn: 'Normal',
          next: 'Normal',
          quickFormat: true,
          run: {
            bold: true,
            size: 32,
            color: '1F4E79',
          },
          paragraph: {
            spacing: { before: 480, after: 240 },
          },
        },
        {
          id: 'Heading2',
          name: 'Heading 2',
          basedOn: 'Normal',
          next: 'Normal',
          quickFormat: true,
          run: {
            bold: true,
            size: 24,
            color: '2E75B6',
          },
          paragraph: {
            spacing: { before: 320, after: 160 },
          },
        },
        {
          id: 'Heading3',
          name: 'Heading 3',
          basedOn: 'Normal',
          next: 'Normal',
          quickFormat: true,
          run: {
            bold: true,
            size: 22,
            color: '404040',
          },
          paragraph: {
            spacing: { before: 240, after: 120 },
          },
        },
      ],
    },
    sections: [
      {
        properties: {
          page: {
            margin: { top: 1440, right: 1440, bottom: 1440, left: 1440, header: 708, footer: 708, gutter: 0 },
            size: { width: 11906, height: 16838 },
          },
        },
        children: [
          // Title
          new Paragraph({
            children: [new TextRun({ text: 'COMPLIANCE REPORT', bold: true, size: 56, color: '1F4E79' })],
            alignment: 'center',
            spacing: { before: 2800, after: 300 },
          }),
          new Paragraph({
            children: [new TextRun({ text: 'Code Migration — Regulatory Mapping', italics: true, size: 28, color: '2E75B6' })],
            alignment: 'center',
            spacing: { after: 200 },
          }),
          
          // Metadata
          new Paragraph({
            children: [new TextRun({ text: `Project: ${data.project.name}`, size: 26, color: '404040' })],
            alignment: 'center',
            spacing: { before: 1200, after: 160 },
          }),
          new Paragraph({
            children: [new TextRun({ text: `Client: ${data.client.name}`, size: 24, color: '404040' })],
            alignment: 'center',
            spacing: { before: 80, after: 80 },
          }),
          new Paragraph({ 
            children: [new TextRun({ text: `Source language: ${data.migration.source_language} → Target language: ${data.migration.target_language}`, size: 24, color: '404040' })],
            alignment: 'center',
            spacing: { before: 80, after: 80 }
          }),
          new Paragraph({
            children: [new TextRun({ text: `Report date: ${data.report.date}`, size: 24, color: '404040' })],
            alignment: 'center',
            spacing: { before: 80, after: 80 },
          }),
          new Paragraph({
            children: [new TextRun({ text: `Report version: ${data.report.version}`, size: 24, color: '404040' })],
            alignment: 'center',
            spacing: { before: 80, after: 80 },
          }),
          new Paragraph({
            children: [new TextRun({ text: `Classification: ${data.report.classification}`, size: 24, color: '404040' })],
            alignment: 'center',
            spacing: { before: 80, after: 80 },
          }),
          
          new Paragraph({
            children: [new TextRun({ text: 'Generated by Scriba', bold: true, color: '1F4E79' })],
            alignment: 'center',
            spacing: { before: 2000, after: 80 },
          }),
          new Paragraph({
            children: [new TextRun({ text: 'AI-Powered Code Migration Platform', italics: true, size: 18, color: '606060' })],
            alignment: 'center',
            spacing: { before: 40, after: 40 },
          }),
          new Paragraph({
            children: [new TextRun({ text: `Scriba AI S.r.l. — ${data.scriba.engine_version}`, size: 18, color: '606060' })],
            alignment: 'center',
            spacing: { before: 40, after: 40 },
          }),

          // Section 1: Report metadata
          new Paragraph({
            text: '1. Report metadata',
            heading: HeadingLevel.HEADING_1,
            spacing: { after: 200 },
          }),

          new Paragraph({ text: '', spacing: { after: 100 } }),
          createMetadataTable(data),
          new Paragraph({ text: '', spacing: { after: 400 } }),

          // Section 2: Executive summary
          new Paragraph({
            text: '2. Executive summary',
            heading: HeadingLevel.HEADING_1,
            spacing: { after: 200 },
          }),
          
          new Paragraph({
            text: 'This report documents the compliance posture of the migrated codebase with respect to the regulatory frameworks selected for this engagement. Findings are produced by Scriba\'s analysis pipeline on the target (post-migration) code and, where relevant, compared against the original (pre-migration) source to identify compliance-relevant deltas.',
            spacing: { after: 200 },
          }),

          new Paragraph({
            text: '2.1 Scope of analysis',
            heading: HeadingLevel.HEADING_2,
            spacing: { after: 100 },
          }),
          new Paragraph({ text: data.summary.scope_description, spacing: { after: 300 } }),

          new Paragraph({
            text: '2.2 Overall compliance posture',
            heading: HeadingLevel.HEADING_2,
            spacing: { after: 100 },
          }),
          new Paragraph({ text: data.summary.overall_posture, spacing: { after: 300 } }),

          new Paragraph({
            text: '2.3 Key metrics',
            heading: HeadingLevel.HEADING_2,
            spacing: { after: 100 },
          }),

          new Paragraph({ text: '', spacing: { after: 100 } }),
          createMetricsTable(data),
          new Paragraph({ text: '', spacing: { after: 400 } }),

          new Paragraph({
            text: '2.4 Top recommendations',
            heading: HeadingLevel.HEADING_2,
            spacing: { after: 100 },
          }),
          ...data.recommendations.map(rec => 
            new Paragraph({ text: `• ${rec}`, spacing: { after: 100 }, bullet: { level: 0 } })
          ),
          new Paragraph({ text: '', spacing: { after: 400 } }),

          // Section 3: Migration context
          new Paragraph({
            text: '3. Migration context',
            heading: HeadingLevel.HEADING_1,
            spacing: { after: 200 },
          }),

          new Paragraph({
            text: '3.1 Source system',
            heading: HeadingLevel.HEADING_2,
            spacing: { after: 100 },
          }),
          new Paragraph({ text: 'Language / runtime:', spacing: { after: 50 } }),
          new Paragraph({ text: data.source.language_runtime, spacing: { after: 100 } }),
          new Paragraph({ text: 'Frameworks and libraries in use:', spacing: { after: 50 } }),
          new Paragraph({ text: data.source.frameworks, spacing: { after: 300 } }),

          new Paragraph({
            text: '3.2 Target system',
            heading: HeadingLevel.HEADING_2,
            spacing: { after: 100 },
          }),
          new Paragraph({ text: 'Language / runtime:', spacing: { after: 50 } }),
          new Paragraph({ text: data.target.language_runtime, spacing: { after: 100 } }),
          new Paragraph({ text: 'Frameworks and libraries introduced:', spacing: { after: 50 } }),
          new Paragraph({ text: data.target.frameworks, spacing: { after: 300 } }),

          new Paragraph({
            text: '3.3 Migration approach',
            heading: HeadingLevel.HEADING_2,
            spacing: { after: 100 },
          }),
          new Paragraph({ text: data.migration_approach, spacing: { after: 300 } }),

          new Paragraph({
            text: '3.4 Compliance-relevant deltas',
            heading: HeadingLevel.HEADING_2,
            spacing: { after: 100 },
          }),
          new Paragraph({
            text: 'The following areas of the codebase present the most significant compliance-relevant differences between source and target:',
            spacing: { after: 200 }
          }),
          ...data.deltas.map(delta => [
            new Paragraph({ text: delta.area, heading: HeadingLevel.HEADING_3, spacing: { after: 100 } }),
            new Paragraph({ text: `Change: ${delta.change_description}`, spacing: { after: 50 } }),
            new Paragraph({ text: `Compliance impact: ${delta.compliance_impact}`, spacing: { after: 50 } }),
            new Paragraph({ text: `Frameworks affected: ${delta.frameworks_affected}`, spacing: { after: 200 } }),
          ]).flat(),

          // Section 4: Analysis methodology
          new Paragraph({
            text: '4. Analysis methodology',
            heading: HeadingLevel.HEADING_1,
            spacing: { after: 200 },
          }),

          new Paragraph({
            text: '4.1 Analysis engines',
            heading: HeadingLevel.HEADING_2,
            spacing: { after: 100 },
          }),
          new Paragraph({ text: data.methodology.engines, spacing: { after: 300 } }),

          new Paragraph({
            text: '4.2 Rule sources',
            heading: HeadingLevel.HEADING_2,
            spacing: { after: 100 },
          }),
          ...data.methodology.rulesource.map((rule: string) =>
            new Paragraph({ text: `• ${rule}`, spacing: { after: 50 }, bullet: { level: 0 } })
          ),
          new Paragraph({ text: '', spacing: { after: 300 } }),

          new Paragraph({
            text: '4.3 Scoring model',
            heading: HeadingLevel.HEADING_2,
            spacing: { after: 100 },
          }),
          new Paragraph({ 
            text: 'Each requirement is evaluated against automated controls and, where applicable, AI-assisted semantic checks. The per-requirement status is one of:',
            spacing: { after: 100 }
          }),
          new Paragraph({ text: 'Met — all controls pass on all in-scope code locations.', spacing: { after: 50 } }),
          new Paragraph({ text: 'Partially met — controls pass on most but not all relevant locations; remediation required.', spacing: { after: 50 } }),
          new Paragraph({ text: 'Not met — one or more controls fail; remediation required.', spacing: { after: 50 } }),
          new Paragraph({ text: 'Not applicable — requirement does not apply to this codebase.', spacing: { after: 100 } }),
          new Paragraph({ 
            text: 'Findings are rated Critical / High / Medium / Low based on exploitability, data sensitivity and regulatory exposure.',
            spacing: { after: 300 }
          }),

          new Paragraph({
            text: '4.4 Limitations and disclaimers',
            heading: HeadingLevel.HEADING_2,
            spacing: { after: 100 },
          }),
          new Paragraph({ text: data.methodology.limitations, spacing: { after: 400 } }),

          // Section 5: Framework applicability
          new Paragraph({
            text: '5. Framework applicability',
            heading: HeadingLevel.HEADING_1,
            spacing: { after: 200 },
          }),
          new Paragraph({
            text: 'The following frameworks have been selected as applicable to this engagement. Frameworks marked as not in scope are listed for transparency and are not evaluated in the remainder of this report.',
            spacing: { after: 200 }
          }),
          new Paragraph({ text: '', spacing: { after: 100 } }),
          createCompatibleTable([
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Framework', bold: true, color: 'FFFFFF' })] })] }),
                  new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'In scope', bold: true, color: 'FFFFFF' })] })] }),
                  new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Rationale', bold: true, color: 'FFFFFF' })] })] }),
                  new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Profile / version', bold: true, color: 'FFFFFF' })] })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'GDPR', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: data.applicability.gdpr.in_scope })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: data.applicability.gdpr.rationale })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: data.applicability.gdpr.profile })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'SOX', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: data.applicability.sox.in_scope })] }),
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: data.applicability.sox.rationale })] }),
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: data.applicability.sox.profile })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'PCI DSS', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: data.applicability.pci.in_scope })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: data.applicability.pci.rationale })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: data.applicability.pci.profile })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'HIPAA', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: data.applicability.hipaa.in_scope })] }),
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: data.applicability.hipaa.rationale })] }),
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: data.applicability.hipaa.profile })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'ISO/IEC 27001', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: data.applicability.iso27001.in_scope })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: data.applicability.iso27001.rationale })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: data.applicability.iso27001.profile })] }),
                ],
              }),
            ], [1400, 1200, 4238, 2800]),
          new Paragraph({ text: '', spacing: { after: 400 } }),

          // Framework-specific sections
          ...createFrameworkSection(6, 'GDPR', 'Regulation (EU) 2016/679', data.gdpr),
          ...createFrameworkSection(7, 'SOX', 'Sarbanes-Oxley Act', data.sox),
          ...createFrameworkSection(8, 'PCI DSS', 'Payment Card Industry Data Security Standard', data.pci),
          ...createFrameworkSection(9, 'HIPAA', 'Health Insurance Portability and Accountability Act', data.hipaa),
          ...createFrameworkSection(10, 'ISO/IEC 27001', 'Information Security Management Systems', data.iso27001),

          // Section 11: Cross-framework control matrix
          new Paragraph({
            text: '11. Cross-framework control matrix',
            heading: HeadingLevel.HEADING_1,
            spacing: { after: 200 },
          }),
          new Paragraph({
            text: 'Controls frequently satisfy requirements across multiple frameworks. This view groups findings by control domain to support efficient remediation planning.',
            spacing: { after: 200 }
          }),
          new Paragraph({ text: '', spacing: { after: 100 } }),
          ...(data.xmatrix.length > 0
            ? [
                createCompatibleTable([
                  new TableRow({
                    children: [
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Control domain', bold: true, color: 'FFFFFF' })] })] }),
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'GDPR', bold: true, color: 'FFFFFF' })] })] }),
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'SOX', bold: true, color: 'FFFFFF' })] })] }),
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'PCI DSS', bold: true, color: 'FFFFFF' })] })] }),
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'HIPAA', bold: true, color: 'FFFFFF' })] })] }),
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'ISO 27001', bold: true, color: 'FFFFFF' })] })] }),
                    ],
                  }),
                  ...data.xmatrix.map((row, idx) =>
                    new TableRow({
                      children: [
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: row.domain, bold: true })] })] }),
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: row.gdpr })] }),
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: row.sox })] }),
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: row.pci })] }),
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: row.hipaa })] }),
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: row.iso27001 })] }),
                      ],
                    })
                  ),
                ], [1900, 1100, 1100, 1200, 1100, 3238]),
              ]
            : [
                new Paragraph({
                  children: [new TextRun({ text: 'No control domains mapped.', italics: true, color: '666666' })],
                  spacing: { after: 200 },
                }),
              ]),
          new Paragraph({ text: '', spacing: { after: 400 } }),

          // Section 12: Remediation plan
          new Paragraph({
            text: '12. Remediation plan',
            heading: HeadingLevel.HEADING_1,
            spacing: { after: 200 },
          }),
          new Paragraph({ 
            text: 'Consolidated remediation items, prioritised by severity and regulatory exposure.',
            spacing: { after: 200 }
          }),
          ...data.remediation.map((rem) => [
            new Paragraph({ text: rem.title, heading: HeadingLevel.HEADING_3, spacing: { after: 100 } }),
            new Paragraph({
              text: `ID: ${rem.id} | Priority: ${rem.priority} | Effort: ${rem.effort}`,
              spacing: { after: 50 }
            }),
            new Paragraph({ text: `Addresses findings: ${rem.findings_refs}`, spacing: { after: 50 } }),
            new Paragraph({ text: `Frameworks impacted: ${rem.frameworks}`, spacing: { after: 100 } }),
            new Paragraph({ children: [new TextRun({ text: 'Description', bold: true })], spacing: { after: 50 } }),
            new Paragraph({ text: rem.description, spacing: { after: 100 } }),
            new Paragraph({ children: [new TextRun({ text: 'Suggested owner:', bold: true })], spacing: { after: 50 } }),
            new Paragraph({ text: rem.owner, spacing: { after: 300 } }),
          ]).flat(),

          // Appendix A: Analysed files
          new Paragraph({
            text: 'Appendix A — Analysed files',
            heading: HeadingLevel.HEADING_1,
            spacing: { after: 200 },
          }),
          new Paragraph({ text: 'Inventory of files included in this analysis.', spacing: { after: 200 } }),
          new Paragraph({ text: '', spacing: { after: 100 } }),
          ...(data.files.length > 0
            ? [
                createCompatibleTable([
                  new TableRow({
                    children: [
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'File path', bold: true, color: 'FFFFFF' })] })] }),
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'LOC', bold: true, color: 'FFFFFF' })] })] }),
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Findings', bold: true, color: 'FFFFFF' })] })] }),
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Max severity', bold: true, color: 'FFFFFF' })] })] }),
                    ],
                  }),
                  ...data.files.map((file, idx) =>
                    new TableRow({
                      children: [
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: file.path })] }),
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: file.loc })] }),
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: file.findings_count })] }),
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: file.max_severity })] }),
                      ],
                    })
                  ),
                ], [5000, 1000, 1600, 2038]),
              ]
            : [
                new Paragraph({
                  children: [new TextRun({ text: 'No files analysed.', italics: true, color: '666666' })],
                  spacing: { after: 200 },
                }),
              ]),
          new Paragraph({ text: '', spacing: { after: 400 } }),

          // Appendix B: Rule inventory
          new Paragraph({
            text: 'Appendix B — Rule inventory',
            heading: HeadingLevel.HEADING_1,
            spacing: { after: 200 },
          }),
          new Paragraph({ text: 'Rules executed in this analysis, with origin and version.', spacing: { after: 200 } }),
          new Paragraph({ text: '', spacing: { after: 100 } }),
          ...(data.rules.length > 0
            ? [
                createCompatibleTable([
                  new TableRow({
                    children: [
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Rule ID', bold: true, color: 'FFFFFF' })] })] }),
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Title', bold: true, color: 'FFFFFF' })] })] }),
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Source pack', bold: true, color: 'FFFFFF' })] })] }),
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Version', bold: true, color: 'FFFFFF' })] })] }),
                      new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Frameworks', bold: true, color: 'FFFFFF' })] })] }),
                    ],
                  }),
                  ...data.rules.map((rule, idx) =>
                    new TableRow({
                      children: [
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: rule.id })] }),
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: rule.title })] }),
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: rule.pack })] }),
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: rule.version })] }),
                        new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: rule.frameworks })] }),
                      ],
                    })
                  ),
                ], [1700, 2600, 1800, 900, 2638]),
              ]
            : [
                new Paragraph({
                  children: [new TextRun({ text: 'No rules executed.', italics: true, color: '666666' })],
                  spacing: { after: 200 },
                }),
              ]),
          new Paragraph({ text: '', spacing: { after: 400 } }),

          // Appendix C: Glossary
          new Paragraph({
            text: 'Appendix C — Glossary',
            heading: HeadingLevel.HEADING_1,
            spacing: { after: 200 },
          }),
          new Paragraph({ text: '', spacing: { after: 100 } }),
          createCompatibleTable([
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Term / Acronym', bold: true, color: 'FFFFFF' })] })] }),
                  new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Definition', bold: true, color: 'FFFFFF' })] })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'CDE', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: 'Cardholder Data Environment — systems that store, process or transmit cardholder data.' })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'CHD', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: 'Cardholder Data — payment card data protected under PCI DSS.' })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'CWE', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: 'Common Weakness Enumeration — community-developed list of software weakness types.' })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'ePHI', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: 'Electronic Protected Health Information under HIPAA.' })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'ICFR', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: 'Internal Control over Financial Reporting — relevant to SOX §404.' })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'ITGC', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: 'IT General Controls — foundation of application controls in SOX audits.' })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'OWASP', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: 'Open Worldwide Application Security Project — application security community and standards.' })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'PII', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: 'Personally Identifiable Information.' })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'SDT', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: 'Structured Document Tag — Word content control enabling programmatic templating.' })] }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'SoA', bold: true })] })] }),
                  new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: 'Statement of Applicability — core ISO/IEC 27001 document.' })] }),
                ],
              }),
            ], [1800, 7838]),
          new Paragraph({ text: '', spacing: { after: 400 } }),

          // Legal disclaimer
          new Paragraph({
            text: 'Appendix D — Legal disclaimer',
            heading: HeadingLevel.HEADING_1,
            spacing: { after: 200 },
          }),
          new Paragraph({
            text: 'This report is a technical artefact produced by automated code analysis. It describes the compliance-relevant characteristics of the migrated codebase at a point in time, based on the rules and configurations applied by the Scriba engine.',
            spacing: { after: 200 },
          }),
          new Paragraph({
            text: 'This report is not a legal opinion, regulatory attestation, certification, audit report, or legal advice. It does not by itself establish or guarantee compliance with any law, regulation or standard. Compliance is a holistic property of people, processes, data flows, deployment environments and organizational controls, the majority of which fall outside the scope of static code analysis.',
            spacing: { after: 200 },
          }),
          new Paragraph({
            text: 'The client remains solely responsible for determining the applicability of any regulation to its business, interpreting the findings of this report in its specific operational context, validating them with competent internal or external advisors (including, where appropriate, legal counsel and qualified auditors), and implementing any remediation or governance measures required.',
            spacing: { after: 200 },
          }),
          new Paragraph({
            text: 'Scriba AI S.r.l. makes no warranty, express or implied, regarding the completeness, accuracy or fitness for purpose of this report, beyond what is expressly agreed in the applicable service agreement.',
            spacing: { after: 200 },
          }),
        ],
      },
    ],
  });

  const buffer = await Packer.toBuffer(doc);
  return buffer;
}

function createMetadataTable(data: ComplianceReportData): Table {
  const rows = [
    ['Project name', data.project.name],
    ['Project ID', data.project.id],
    ['Client organization', data.client.name],
    ['Repository / codebase', data.project.repository],
    ['Source language & version', data.migration.source_language],
    ['Target language & version', data.migration.target_language],
    ['Migration job ID', data.migration.job_id],
    ['Migration date', data.migration.date],
    ['Report generated on', data.report.date],
    ['Report version', data.report.version],
    ['Classification', data.report.classification],
    ['Scriba engine version', data.scriba.engine_version],
    ['Applicable frameworks', data.frameworks.list],
  ];

  return createCompatibleTable(
    [
      new TableRow({
        children: [
          new TableCell({
            shading: { fill: '1F4E79', color: 'auto' },
            children: [new Paragraph({ children: [new TextRun({ text: 'Field', bold: true, color: 'FFFFFF' })] })],
          }),
          new TableCell({
            shading: { fill: '1F4E79', color: 'auto' },
            children: [new Paragraph({ children: [new TextRun({ text: 'Value', bold: true, color: 'FFFFFF' })] })],
          }),
        ],
      }),
      ...rows.map(([label, value], idx) =>
        new TableRow({
          children: [
            new TableCell({
              shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' },
              children: [new Paragraph({ children: [new TextRun({ text: label, bold: true })] })],
            }),
            new TableCell({
              shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' },
              children: [new Paragraph({ text: value })],
            }),
          ],
        })
      ),
    ],
    [TABLE_WIDTH_40, TABLE_WIDTH_60]
  );
}

function createMetricsTable(data: ComplianceReportData): Table {
  const rows = [
    ['Files analysed', data.metrics.files_analyzed, data.metrics.files_analyzed_delta, data.metrics.files_analyzed_trend],
    ['Lines of code (target)', data.metrics.loc_target, data.metrics.loc_target_delta, data.metrics.loc_target_trend],
    ['Total requirements evaluated', data.metrics.req_total, data.metrics.req_total_delta, data.metrics.req_total_trend],
    ['Requirements met', data.metrics.req_met, data.metrics.req_met_delta, data.metrics.req_met_trend],
    ['Requirements partially met', data.metrics.req_partial, data.metrics.req_partial_delta, data.metrics.req_partial_trend],
    ['Requirements not met', data.metrics.req_not_met, data.metrics.req_not_met_delta, data.metrics.req_not_met_trend],
    ['Requirements not applicable', data.metrics.req_na, data.metrics.req_na_delta, data.metrics.req_na_trend],
    ['Critical findings', data.metrics.findings_critical, data.metrics.findings_critical_delta, data.metrics.findings_critical_trend],
    ['High findings', data.metrics.findings_high, data.metrics.findings_high_delta, data.metrics.findings_high_trend],
    ['Medium findings', data.metrics.findings_medium, data.metrics.findings_medium_delta, data.metrics.findings_medium_trend],
    ['Low / informational findings', data.metrics.findings_low, data.metrics.findings_low_delta, data.metrics.findings_low_trend],
    ['Overall compliance score (0–100)', data.metrics.compliance_score, data.metrics.compliance_score_delta, data.metrics.compliance_score_trend],
  ];

  return createCompatibleTable(
    [
      new TableRow({
        children: [
          new TableCell({
            shading: { fill: '1F4E79', color: 'auto' },
            children: [new Paragraph({ children: [new TextRun({ text: 'Metric', bold: true, color: 'FFFFFF' })] })],
          }),
          new TableCell({
            shading: { fill: '1F4E79', color: 'auto' },
            children: [new Paragraph({ children: [new TextRun({ text: 'Value', bold: true, color: 'FFFFFF' })] })],
          }),
          new TableCell({
            shading: { fill: '1F4E79', color: 'auto' },
            children: [new Paragraph({ children: [new TextRun({ text: 'Delta vs source', bold: true, color: 'FFFFFF' })] })],
          }),
          new TableCell({
            shading: { fill: '1F4E79', color: 'auto' },
            children: [new Paragraph({ children: [new TextRun({ text: 'Trend', bold: true, color: 'FFFFFF' })] })],
          }),
        ],
      }),
      ...rows.map(([label, value, delta, trend], idx) =>
        new TableRow({
          children: [
            new TableCell({
              shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' },
              children: [new Paragraph({ children: [new TextRun({ text: label, bold: true })] })],
            }),
            new TableCell({
              shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' },
              children: [new Paragraph({ text: value })],
            }),
            new TableCell({
              shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' },
              children: [new Paragraph({ text: delta })],
            }),
            new TableCell({
              shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' },
              children: [new Paragraph({ text: trend })],
            }),
          ],
        })
      ),
    ],
    [3600, 1300, 2500, 2238]
  );
}

interface FrameworkData {
  summary: string;
  scorecard: {
    met: { count: string; pct: string; delta: string };
    partial: { count: string; pct: string; delta: string };
    not_met: { count: string; pct: string; delta: string };
    na: { count: string; pct: string; delta: string };
    score: { count: string; pct: string; delta: string };
  };
  requirements: Array<{
    id: string;
    description: string;
    control_evidence: string;
    status: string;
    code_locations: string;
  }>;
  findings: Array<{
    title: string;
    id: string;
    severity: string;
    requirement_ref: string;
    description: string;
    file: string;
    lines: string;
    symbol: string;
    code_snippet: string;
    source_snippet: string;
    recommendation: string;
    references: string;
  }>;
  specific_notes: string;
}

function createFrameworkSection(
  sectionNumber: number,
  name: string,
  subtitle: string,
  framework: FrameworkData
): (Paragraph | Table)[] {
  const content: (Paragraph | Table)[] = [];

  content.push(
    new Paragraph({
      text: `${sectionNumber}. ${name} — ${subtitle}`,
      heading: HeadingLevel.HEADING_1,
      spacing: { after: 200 },
    }),
    new Paragraph({
      text: 'Summary',
      heading: HeadingLevel.HEADING_2,
      spacing: { after: 100 },
    }),
    new Paragraph({ text: framework.summary, spacing: { after: 300 } }),
    new Paragraph({
      text: 'Scorecard',
      heading: HeadingLevel.HEADING_2,
      spacing: { after: 100 },
    }),
    new Paragraph({ text: '', spacing: { after: 50 } }),
    createCompatibleTable([
        new TableRow({
          children: [
            new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Metric', bold: true, color: 'FFFFFF' })] })] }),
            new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Count', bold: true, color: 'FFFFFF' })] })] }),
            new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: '% of total', bold: true, color: 'FFFFFF' })] })] }),
            new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Δ vs source', bold: true, color: 'FFFFFF' })] })] }),
          ],
        }),
        new TableRow({
          children: [
            new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Requirements met', bold: true })] })] }),
            new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.met.count })] }),
            new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.met.pct })] }),
            new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.met.delta })] }),
          ],
        }),
        new TableRow({
          children: [
            new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Partially met', bold: true })] })] }),
            new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.partial.count })] }),
            new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.partial.pct })] }),
            new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.partial.delta })] }),
          ],
        }),
        new TableRow({
          children: [
            new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Not met', bold: true })] })] }),
            new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.not_met.count })] }),
            new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.not_met.pct })] }),
            new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.not_met.delta })] }),
          ],
        }),
        new TableRow({
          children: [
            new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Not applicable', bold: true })] })] }),
            new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.na.count })] }),
            new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.na.pct })] }),
            new TableCell({ shading: { fill: 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.na.delta })] }),
          ],
        }),
        new TableRow({
          children: [
            new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Compliance score (0–100)', bold: true })] })] }),
            new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.score.count })] }),
            new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.score.pct })] }),
            new TableCell({ shading: { fill: 'EEF3F8', color: 'auto' }, children: [new Paragraph({ text: framework.scorecard.score.delta })] }),
          ],
        }),
      ], [3600, 1200, 1600, 3238]),
    new Paragraph({ text: '', spacing: { after: 300 } }),
    new Paragraph({
      text: 'Requirement mapping',
      heading: HeadingLevel.HEADING_2,
      spacing: { after: 100 },
    }),
    new Paragraph({
      text: 'Each row maps a requirement from the framework to the controls applied in the migrated codebase.',
      spacing: { after: 200 }
    }),
    new Paragraph({ text: '', spacing: { after: 50 } }),
    ...(framework.requirements.length > 0
      ? [
          createCompatibleTable([
            new TableRow({
              children: [
                new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Requirement ID', bold: true, color: 'FFFFFF' })] })] }),
                new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Requirement description', bold: true, color: 'FFFFFF' })] })] }),
                new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Control / evidence in code', bold: true, color: 'FFFFFF' })] })] }),
                new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Status', bold: true, color: 'FFFFFF' })] })] }),
                new TableCell({ shading: { fill: '1F4E79', color: 'auto' }, children: [new Paragraph({ children: [new TextRun({ text: 'Code locations', bold: true, color: 'FFFFFF' })] })] }),
              ],
            }),
            ...framework.requirements.map((req, idx) =>
              new TableRow({
                children: [
                  new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: req.id })] }),
                  new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: req.description })] }),
                  new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: req.control_evidence })] }),
                  new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: req.status })] }),
                  new TableCell({ shading: { fill: idx % 2 === 0 ? 'EEF3F8' : 'FFFFFF', color: 'auto' }, children: [new Paragraph({ text: req.code_locations })] }),
                ],
              })
            ),
          ], [1200, 2600, 2500, 900, 2438]),
        ]
      : [
          new Paragraph({
            children: [new TextRun({ text: 'No requirements mapped.', italics: true, color: '666666' })],
            spacing: { after: 200 },
          }),
        ]),
    new Paragraph({ text: '', spacing: { after: 200 } }),
    new Paragraph({ text: 'Status legend: Met · Partially met · Not met · Not applicable', spacing: { after: 300 } }),
    new Paragraph({
      text: 'Findings',
      heading: HeadingLevel.HEADING_2,
      spacing: { after: 100 },
    }),
    new Paragraph({
      text: 'Each finding below identifies a specific location in the migrated codebase where a requirement of this framework is not fully satisfied.',
      spacing: { after: 200 }
    }),
    ...framework.findings.map((finding) => [
      new Paragraph({ text: finding.title, heading: HeadingLevel.HEADING_3, spacing: { after: 100 } }),
      new Paragraph({
        text: `Finding ID: ${finding.id} | Severity: ${finding.severity} | Requirement: ${finding.requirement_ref}`,
        spacing: { after: 100 }
      }),
      new Paragraph({ children: [new TextRun({ text: 'Description', bold: true })], spacing: { after: 50 } }),
      new Paragraph({ text: finding.description, spacing: { after: 100 } }),
      new Paragraph({ children: [new TextRun({ text: 'Code location', bold: true })], spacing: { after: 50 } }),
      new Paragraph({
        text: `File: ${finding.file} | Lines: ${finding.lines} | Function/class: ${finding.symbol}`,
        spacing: { after: 100 }
      }),
      new Paragraph({ children: [new TextRun({ text: 'Evidence snippet (target code)', bold: true })], spacing: { after: 50 } }),
      new Paragraph({ text: finding.code_snippet, spacing: { after: 100 } }),
      new Paragraph({ children: [new TextRun({ text: 'Source counterpart (pre-migration)', bold: true })], spacing: { after: 50 } }),
      new Paragraph({ text: finding.source_snippet, spacing: { after: 100 } }),
      new Paragraph({ children: [new TextRun({ text: 'Recommendation', bold: true })], spacing: { after: 50 } }),
      new Paragraph({ text: finding.recommendation, spacing: { after: 100 } }),
      new Paragraph({ children: [new TextRun({ text: 'References', bold: true })], spacing: { after: 50 } }),
      new Paragraph({ text: finding.references, spacing: { after: 300 } }),
    ]).flat(),
    new Paragraph({
      text: 'Framework-specific notes',
      heading: HeadingLevel.HEADING_2,
      spacing: { after: 100 },
    }),
    new Paragraph({ text: framework.specific_notes, spacing: { after: 400 } }),
  );

  return content;
}

export function getDefaultComplianceReportData(projectName: string): ComplianceReportData {
  const today = new Date().toISOString().split('T')[0];
  
  return {
    project: {
      name: projectName,
      id: 'proj-' + Math.random().toString(36).substr(2, 9),
      repository: 'N/A',
    },
    client: {
      name: 'N/A',
    },
    migration: {
      source_language: 'N/A',
      target_language: 'N/A',
      job_id: 'N/A',
      date: today,
    },
    report: {
      date: today,
      version: '1.0',
      classification: 'Confidential',
    },
    scriba: {
      engine_version: '1.0.0',
    },
    frameworks: {
      list: 'GDPR, SOX, PCI DSS, HIPAA, ISO/IEC 27001',
    },
    summary: {
      scope_description: 'Compliance report generated from available project metadata. Detailed analysis data was not provided.',
      overall_posture: 'Insufficient data to determine compliance posture. Provide analysis results for framework-level findings and scoring.',
    },
    metrics: {
      files_analyzed: '0', files_analyzed_delta: 'N/A', files_analyzed_trend: 'N/A',
      loc_target: '0', loc_target_delta: 'N/A', loc_target_trend: 'N/A',
      req_total: '0', req_total_delta: 'N/A', req_total_trend: 'N/A',
      req_met: '0', req_met_delta: 'N/A', req_met_trend: 'N/A',
      req_partial: '0', req_partial_delta: 'N/A', req_partial_trend: 'N/A',
      req_not_met: '0', req_not_met_delta: 'N/A', req_not_met_trend: 'N/A',
      req_na: '0', req_na_delta: 'N/A', req_na_trend: 'N/A',
      findings_critical: '0', findings_critical_delta: 'N/A', findings_critical_trend: 'N/A',
      findings_high: '0', findings_high_delta: 'N/A', findings_high_trend: 'N/A',
      findings_medium: '0', findings_medium_delta: 'N/A', findings_medium_trend: 'N/A',
      findings_low: '0', findings_low_delta: 'N/A', findings_low_trend: 'N/A',
      compliance_score: 'N/A', compliance_score_delta: 'N/A', compliance_score_trend: 'N/A',
    },
    recommendations: [
      'Connect analysis outputs to populate requirement mappings and findings.',
      'Review selected frameworks and confirm scope with compliance stakeholders.',
      'Validate repository metadata and runtime information before export.',
      'Attach remediation actions once security/compliance scans are completed.',
    ],
    source: {
      language_runtime: 'N/A',
      frameworks: 'N/A',
    },
    target: {
      language_runtime: 'N/A',
      frameworks: 'N/A',
    },
    migration_approach: 'N/A',
    deltas: [],
    methodology: {
      engines: 'Static analysis (ESLint/SonarQube), AI semantic analysis, pattern matching',
      rulesource: ['Configured policy/rule packs'],
      limitations: 'Analysis data not attached. This report includes metadata only until analysis outputs are provided.',
    },
    applicability: {
      gdpr: { in_scope: 'Not determined', rationale: 'Scope not yet assessed — confirm with compliance stakeholders.', profile: 'Regulation (EU) 2016/679' },
      sox: { in_scope: 'Not determined', rationale: 'Scope not yet assessed — confirm with compliance stakeholders.', profile: 'Sarbanes-Oxley Act (2002) §302 / §404' },
      pci: { in_scope: 'Not determined', rationale: 'Scope not yet assessed — confirm with compliance stakeholders.', profile: 'PCI DSS v4.0 (March 2022)' },
      hipaa: { in_scope: 'Not determined', rationale: 'Scope not yet assessed — confirm with compliance stakeholders.', profile: 'HIPAA Security Rule (45 CFR §164.302–318)' },
      iso27001: { in_scope: 'Not determined', rationale: 'Scope not yet assessed — confirm with compliance stakeholders.', profile: 'ISO/IEC 27001:2022' },
    },
    gdpr: {
      summary: 'No framework-specific analysis data provided.',
      scorecard: {
        met: { count: '0', pct: '0%', delta: 'N/A' },
        partial: { count: '0', pct: '0%', delta: 'N/A' },
        not_met: { count: '0', pct: '0%', delta: 'N/A' },
        na: { count: '0', pct: '0%', delta: 'N/A' },
        score: { count: 'N/A', pct: 'N/A', delta: 'N/A' },
      },
      requirements: [],
      findings: [],
      specific_notes: 'No data provided.',
    },
    sox: {
      summary: 'No framework-specific analysis data provided.',
      scorecard: {
        met: { count: '0', pct: '0%', delta: 'N/A' },
        partial: { count: '0', pct: '0%', delta: 'N/A' },
        not_met: { count: '0', pct: '0%', delta: 'N/A' },
        na: { count: '0', pct: '0%', delta: 'N/A' },
        score: { count: 'N/A', pct: 'N/A', delta: 'N/A' },
      },
      requirements: [],
      findings: [],
      specific_notes: 'No data provided.',
    },
    pci: {
      summary: 'No framework-specific analysis data provided.',
      scorecard: {
        met: { count: '0', pct: '0%', delta: 'N/A' },
        partial: { count: '0', pct: '0%', delta: 'N/A' },
        not_met: { count: '0', pct: '0%', delta: 'N/A' },
        na: { count: '0', pct: '0%', delta: 'N/A' },
        score: { count: 'N/A', pct: 'N/A', delta: 'N/A' },
      },
      requirements: [],
      findings: [],
      specific_notes: 'No data provided.',
    },
    hipaa: {
      summary: 'No framework-specific analysis data provided.',
      scorecard: {
        met: { count: '0', pct: '0%', delta: '0' },
        partial: { count: '0', pct: '0%', delta: '0' },
        not_met: { count: '0', pct: '0%', delta: '0' },
        na: { count: '0', pct: '0%', delta: '0' },
        score: { count: 'N/A', pct: 'N/A', delta: 'N/A' },
      },
      requirements: [],
      findings: [],
      specific_notes: 'No data provided.',
    },
    iso27001: {
      summary: 'No framework-specific analysis data provided.',
      scorecard: {
        met: { count: '0', pct: '0%', delta: 'N/A' },
        partial: { count: '0', pct: '0%', delta: 'N/A' },
        not_met: { count: '0', pct: '0%', delta: 'N/A' },
        na: { count: '0', pct: '0%', delta: 'N/A' },
        score: { count: 'N/A', pct: 'N/A', delta: 'N/A' },
      },
      requirements: [],
      findings: [],
      specific_notes: 'No data provided.',
    },
    xmatrix: [],
    remediation: [],
    files: [],
    rules: [],
  };
}
