// =============================================================================
// TOM Document — HTML Document Builder (main entry point)
// =============================================================================

import type {
  TOMGeneratorState,
  DerivedTOM,
  CompanyProfile,
  RiskProfile,
  ControlCategory,
} from '../tom-generator/types'
import { SDM_CATEGORY_MAPPING } from '../tom-generator/types'
import {
  getControlById,
  getAllCategories,
} from '../tom-generator/controls/loader'
import type { TOMComplianceCheckResult } from '../tom-compliance'
import type { TOMDocumentOrgHeader, TOMDocumentRevision } from './types-defaults'
import { CATEGORY_LABELS_DE } from './types-defaults'
import { escHtml, formatDateDE } from './helpers'
import { buildDocumentStyles } from './html-styles'
import { buildSections1to6 } from './html-sections-1-6'
import { buildSections7to11 } from './html-sections-7-11'

export function buildTOMDocumentHtml(
  derivedTOMs: DerivedTOM[],
  orgHeader: TOMDocumentOrgHeader,
  companyProfile: CompanyProfile | null,
  riskProfile: RiskProfile | null,
  complianceResult: TOMComplianceCheckResult | null,
  revisions: TOMDocumentRevision[]
): string {
  const today = new Date().toLocaleDateString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  })

  const orgName = orgHeader.organizationName || 'Organisation'
  const applicableTOMs = derivedTOMs.filter(t => t.applicability !== 'NOT_APPLICABLE')

  // Group TOMs by category
  const tomsByCategory = new Map<ControlCategory, DerivedTOM[]>()
  for (const tom of applicableTOMs) {
    const control = getControlById(tom.controlId)
    const cat = control?.category || 'REVIEW'
    if (!tomsByCategory.has(cat)) tomsByCategory.set(cat, [])
    tomsByCategory.get(cat)!.push(tom)
  }

  // Build role map
  const roleMap = new Map<string, string[]>()
  for (const tom of applicableTOMs) {
    const role = tom.responsiblePerson || tom.responsibleDepartment || 'Nicht zugewiesen'
    if (!roleMap.has(role)) roleMap.set(role, [])
    const control = getControlById(tom.controlId)
    roleMap.get(role)!.push(control?.code || tom.controlId)
  }

  let html = buildDocumentStyles(escHtml(orgName))

  html += buildSections1to6(
    orgName, orgHeader, companyProfile, riskProfile,
    applicableTOMs, tomsByCategory, today
  )

  html += buildSections7to11(
    orgName, orgHeader, tomsByCategory, roleMap,
    complianceResult, revisions, today
  )

  html += `
<div class="page-footer">
  <span>TOM-Dokumentation — ${escHtml(orgName)}</span>
  <span>Stand: ${today} | Version ${escHtml(orgHeader.documentVersion)}</span>
</div>

</body>
</html>`

  return html
}
