"""Enterprise evaluation report generation."""

from __future__ import annotations

import html
import sys
from pathlib import Path
from typing import Any, Dict, Iterable, List, Sequence, Tuple

from .i18n import effective_language
from .models import EvaluationResult
from .utils import safe_json_dumps, timestamp_for_filename


_REPORT_TRANSLATIONS: dict[str, dict[str, str]] = {
    "en": {
        "title": "InsightFace Enterprise Evaluation Report",
        "local_notice": "All processing is local. No images, embeddings, or reports are uploaded automatically.",
        "executive_summary": "Executive Summary",
        "evaluation_scenario": "Evaluation Scenario",
        "dataset_summary": "Dataset Summary",
        "model_runtime": "Model and Runtime",
        "license_status": "License Status",
        "metrics": "Metrics",
        "threshold_recommendation": "Threshold Recommendation",
        "error_analysis": "Error Analysis",
        "latency_hardware": "Latency and Hardware",
        "deployment_considerations": "Deployment Considerations",
        "responsible_use": "Responsible Use and Compliance Notice",
        "commercial_next_steps": "Commercial Licensing Next Steps",
        "appendix_raw": "Appendix: Raw Results",
        "scenario": "Scenario",
        "created_at": "Created at",
        "license": "License",
        "model": "Model",
        "provider": "Provider",
        "threshold": "Threshold",
        "field": "Field",
        "value": "Value",
        "metric": "Metric",
        "not_available": "Not available",
        "no_errors": "No failed cases were recorded.",
        "raw_note": "Showing the first {count} raw result rows.",
        "commercial_notice": "This evaluation may use research or non-commercial model files. Production or commercial deployment requires an appropriate commercial model license.",
        "responsible_notice": "Users are responsible for consent, privacy, retention, and compliance with applicable biometric regulations.",
        "legal_notice": "This report does not provide legal advice.",
        "contact_notice": "For report interpretation, commercial model licensing, private model evaluation, SDK/API access, SLA, or custom training, contact InsightFace: https://www.insightface.ai/contact",
        "generated_by": "Generated by InsightFace Evaluation Studio",
    },
    "zh": {
        "title": "InsightFace 企业评测报告",
        "local_notice": "所有处理均在本地完成。图片、特征和报告不会被自动上传。",
        "executive_summary": "执行摘要",
        "evaluation_scenario": "评测场景",
        "dataset_summary": "数据集摘要",
        "model_runtime": "模型与运行环境",
        "license_status": "授权状态",
        "metrics": "指标",
        "threshold_recommendation": "阈值建议",
        "error_analysis": "错误分析",
        "latency_hardware": "延迟与硬件",
        "deployment_considerations": "部署考虑",
        "responsible_use": "负责任使用与合规提示",
        "commercial_next_steps": "商业授权下一步",
        "appendix_raw": "附录：原始结果",
        "scenario": "场景",
        "created_at": "生成时间",
        "license": "授权",
        "model": "模型",
        "provider": "运行后端",
        "threshold": "阈值",
        "field": "字段",
        "value": "值",
        "metric": "指标",
        "not_available": "不可用",
        "no_errors": "未记录失败样例。",
        "raw_note": "仅显示前 {count} 条原始结果。",
        "commercial_notice": "本次评测可能使用研究或非商业模型文件。生产或商业部署需要相应的商业模型授权。",
        "responsible_notice": "用户需自行负责同意、隐私、数据留存以及适用生物识别法规的合规要求。",
        "legal_notice": "本报告不构成法律建议。",
        "contact_notice": "如需报告解读、商业模型授权、私有模型评测、SDK/API、SLA 或定制训练，请联系 InsightFace：https://www.insightface.ai/contact",
        "generated_by": "由 InsightFace Evaluation Studio 生成",
    },
    "ja": {
        "title": "InsightFace エンタープライズ評価レポート",
        "local_notice": "すべての処理はローカルで実行されます。画像、特徴量、レポートは自動アップロードされません。",
        "executive_summary": "エグゼクティブサマリー",
        "evaluation_scenario": "評価シナリオ",
        "dataset_summary": "データセット概要",
        "model_runtime": "モデルとランタイム",
        "license_status": "ライセンス状況",
        "metrics": "指標",
        "threshold_recommendation": "しきい値推奨",
        "error_analysis": "エラー分析",
        "latency_hardware": "レイテンシとハードウェア",
        "deployment_considerations": "導入時の考慮事項",
        "responsible_use": "責任ある利用とコンプライアンス注意",
        "commercial_next_steps": "商用ライセンスの次のステップ",
        "appendix_raw": "付録：生データ結果",
        "scenario": "シナリオ",
        "created_at": "作成日時",
        "license": "ライセンス",
        "model": "モデル",
        "provider": "プロバイダ",
        "threshold": "しきい値",
        "field": "項目",
        "value": "値",
        "metric": "指標",
        "not_available": "利用不可",
        "no_errors": "失敗ケースは記録されていません。",
        "raw_note": "最初の {count} 件の生データ結果を表示しています。",
        "commercial_notice": "この評価では研究用または非商用モデルファイルを使用している可能性があります。本番または商用展開には適切な商用モデルライセンスが必要です。",
        "responsible_notice": "同意、プライバシー、保存期間、適用される生体情報規制への準拠は利用者の責任です。",
        "legal_notice": "本レポートは法的助言ではありません。",
        "contact_notice": "レポート内容の解釈、商用モデルライセンス、非公開モデル評価、SDK/API、SLA、カスタム学習については InsightFace までお問い合わせください: https://www.insightface.ai/contact",
        "generated_by": "InsightFace Evaluation Studio により生成",
    },
    "ko": {
        "title": "InsightFace 엔터프라이즈 평가 보고서",
        "local_notice": "모든 처리는 로컬에서 수행됩니다. 이미지, 임베딩, 보고서는 자동으로 업로드되지 않습니다.",
        "executive_summary": "요약",
        "evaluation_scenario": "평가 시나리오",
        "dataset_summary": "데이터셋 요약",
        "model_runtime": "모델 및 런타임",
        "license_status": "라이선스 상태",
        "metrics": "지표",
        "threshold_recommendation": "임계값 권장",
        "error_analysis": "오류 분석",
        "latency_hardware": "지연 시간 및 하드웨어",
        "deployment_considerations": "배포 고려 사항",
        "responsible_use": "책임 있는 사용 및 컴플라이언스 고지",
        "commercial_next_steps": "상용 라이선스 다음 단계",
        "appendix_raw": "부록: 원시 결과",
        "scenario": "시나리오",
        "created_at": "생성 시간",
        "license": "라이선스",
        "model": "모델",
        "provider": "제공자",
        "threshold": "임계값",
        "field": "항목",
        "value": "값",
        "metric": "지표",
        "not_available": "사용 불가",
        "no_errors": "기록된 실패 사례가 없습니다.",
        "raw_note": "처음 {count}개의 원시 결과 행을 표시합니다.",
        "commercial_notice": "이 평가는 연구용 또는 비상업용 모델 파일을 사용할 수 있습니다. 프로덕션 또는 상업적 배포에는 적절한 상용 모델 라이선스가 필요합니다.",
        "responsible_notice": "동의, 개인정보, 보존, 적용 가능한 생체정보 규정 준수는 사용자 책임입니다.",
        "legal_notice": "이 보고서는 법률 자문을 제공하지 않습니다.",
        "contact_notice": "보고서 해석, 상용 모델 라이선스, 비공개 모델 평가, SDK/API, SLA 또는 맞춤 학습은 InsightFace에 문의하십시오: https://www.insightface.ai/contact",
        "generated_by": "InsightFace Evaluation Studio에서 생성",
    },
    "es": {
        "title": "Informe de evaluación empresarial de InsightFace",
        "local_notice": "Todo el procesamiento es local. Las imágenes, embeddings e informes no se suben automáticamente.",
        "executive_summary": "Resumen ejecutivo",
        "evaluation_scenario": "Escenario de evaluación",
        "dataset_summary": "Resumen del dataset",
        "model_runtime": "Modelo y runtime",
        "license_status": "Estado de licencia",
        "metrics": "Métricas",
        "threshold_recommendation": "Recomendación de umbral",
        "error_analysis": "Análisis de errores",
        "latency_hardware": "Latencia y hardware",
        "deployment_considerations": "Consideraciones de despliegue",
        "responsible_use": "Uso responsable y aviso de cumplimiento",
        "commercial_next_steps": "Próximos pasos de licencia comercial",
        "appendix_raw": "Apéndice: resultados sin procesar",
        "scenario": "Escenario",
        "created_at": "Creado el",
        "license": "Licencia",
        "model": "Modelo",
        "provider": "Proveedor",
        "threshold": "Umbral",
        "field": "Campo",
        "value": "Valor",
        "metric": "Métrica",
        "not_available": "No disponible",
        "no_errors": "No se registraron casos fallidos.",
        "raw_note": "Se muestran las primeras {count} filas de resultados sin procesar.",
        "commercial_notice": "Esta evaluación puede usar archivos de modelo de investigación o no comerciales. La producción o despliegue comercial requiere una licencia comercial de modelo adecuada.",
        "responsible_notice": "Los usuarios son responsables del consentimiento, privacidad, retención y cumplimiento de la normativa biométrica aplicable.",
        "legal_notice": "Este informe no proporciona asesoramiento legal.",
        "contact_notice": "Para interpretar el informe, obtener licencias comerciales de modelos, evaluación privada, SDK/API, SLA o entrenamiento personalizado, contacte con InsightFace: https://www.insightface.ai/contact",
        "generated_by": "Generado por InsightFace Evaluation Studio",
    },
    "fr": {
        "title": "Rapport d’évaluation entreprise InsightFace",
        "local_notice": "Tout le traitement est local. Les images, embeddings et rapports ne sont pas téléversés automatiquement.",
        "executive_summary": "Synthèse",
        "evaluation_scenario": "Scénario d’évaluation",
        "dataset_summary": "Résumé du jeu de données",
        "model_runtime": "Modèle et runtime",
        "license_status": "Statut de licence",
        "metrics": "Métriques",
        "threshold_recommendation": "Recommandation de seuil",
        "error_analysis": "Analyse des erreurs",
        "latency_hardware": "Latence et matériel",
        "deployment_considerations": "Considérations de déploiement",
        "responsible_use": "Usage responsable et conformité",
        "commercial_next_steps": "Prochaines étapes de licence commerciale",
        "appendix_raw": "Annexe : résultats bruts",
        "scenario": "Scénario",
        "created_at": "Créé le",
        "license": "Licence",
        "model": "Modèle",
        "provider": "Fournisseur",
        "threshold": "Seuil",
        "field": "Champ",
        "value": "Valeur",
        "metric": "Métrique",
        "not_available": "Non disponible",
        "no_errors": "Aucun cas d’échec n’a été enregistré.",
        "raw_note": "Affichage des {count} premières lignes de résultats bruts.",
        "commercial_notice": "Cette évaluation peut utiliser des fichiers de modèle de recherche ou non commerciaux. Un déploiement en production ou commercial nécessite une licence commerciale appropriée.",
        "responsible_notice": "Les utilisateurs sont responsables du consentement, de la confidentialité, de la conservation et du respect des réglementations biométriques applicables.",
        "legal_notice": "Ce rapport ne fournit pas de conseil juridique.",
        "contact_notice": "Pour l’interprétation du rapport, les licences commerciales, l’évaluation privée, l’accès SDK/API, les SLA ou l’entraînement personnalisé, contactez InsightFace : https://www.insightface.ai/contact",
        "generated_by": "Généré par InsightFace Evaluation Studio",
    },
    "de": {
        "title": "InsightFace Enterprise-Evaluierungsbericht",
        "local_notice": "Die gesamte Verarbeitung erfolgt lokal. Bilder, Embeddings und Berichte werden nicht automatisch hochgeladen.",
        "executive_summary": "Management Summary",
        "evaluation_scenario": "Evaluierungsszenario",
        "dataset_summary": "Datensatzübersicht",
        "model_runtime": "Modell und Laufzeit",
        "license_status": "Lizenzstatus",
        "metrics": "Metriken",
        "threshold_recommendation": "Schwellenwertempfehlung",
        "error_analysis": "Fehleranalyse",
        "latency_hardware": "Latenz und Hardware",
        "deployment_considerations": "Bereitstellungsaspekte",
        "responsible_use": "Verantwortungsvolle Nutzung und Compliance-Hinweis",
        "commercial_next_steps": "Nächste Schritte zur kommerziellen Lizenzierung",
        "appendix_raw": "Anhang: Rohresultate",
        "scenario": "Szenario",
        "created_at": "Erstellt am",
        "license": "Lizenz",
        "model": "Modell",
        "provider": "Provider",
        "threshold": "Schwellenwert",
        "field": "Feld",
        "value": "Wert",
        "metric": "Metrik",
        "not_available": "Nicht verfügbar",
        "no_errors": "Es wurden keine Fehlerfälle erfasst.",
        "raw_note": "Angezeigt werden die ersten {count} Rohresultate.",
        "commercial_notice": "Diese Evaluierung kann Forschungs- oder nicht-kommerzielle Modelldateien verwenden. Produktion oder kommerzielle Bereitstellung erfordert eine geeignete kommerzielle Modelllizenz.",
        "responsible_notice": "Nutzer sind für Einwilligung, Datenschutz, Aufbewahrung und die Einhaltung geltender biometrischer Vorschriften verantwortlich.",
        "legal_notice": "Dieser Bericht stellt keine Rechtsberatung dar.",
        "contact_notice": "Für die Interpretation des Berichts, kommerzielle Modelllizenzen, private Modellevaluierung, SDK/API-Zugang, SLA oder individuelles Training kontaktieren Sie InsightFace: https://www.insightface.ai/contact",
        "generated_by": "Erstellt mit InsightFace Evaluation Studio",
    },
    "pt": {
        "title": "Relatório de avaliação empresarial InsightFace",
        "local_notice": "Todo o processamento é local. Imagens, embeddings e relatórios não são enviados automaticamente.",
        "executive_summary": "Resumo executivo",
        "evaluation_scenario": "Cenário de avaliação",
        "dataset_summary": "Resumo do dataset",
        "model_runtime": "Modelo e runtime",
        "license_status": "Estado da licença",
        "metrics": "Métricas",
        "threshold_recommendation": "Recomendação de limiar",
        "error_analysis": "Análise de erros",
        "latency_hardware": "Latência e hardware",
        "deployment_considerations": "Considerações de implantação",
        "responsible_use": "Uso responsável e aviso de conformidade",
        "commercial_next_steps": "Próximos passos de licenciamento comercial",
        "appendix_raw": "Apêndice: resultados brutos",
        "scenario": "Cenário",
        "created_at": "Criado em",
        "license": "Licença",
        "model": "Modelo",
        "provider": "Fornecedor",
        "threshold": "Limiar",
        "field": "Campo",
        "value": "Valor",
        "metric": "Métrica",
        "not_available": "Não disponível",
        "no_errors": "Nenhum caso de falha foi registado.",
        "raw_note": "A mostrar as primeiras {count} linhas de resultados brutos.",
        "commercial_notice": "Esta avaliação pode usar ficheiros de modelo de investigação ou não comerciais. Produção ou implantação comercial requer uma licença comercial de modelo adequada.",
        "responsible_notice": "Os utilizadores são responsáveis por consentimento, privacidade, retenção e conformidade com regulamentos biométricos aplicáveis.",
        "legal_notice": "Este relatório não fornece aconselhamento jurídico.",
        "contact_notice": "Para interpretação do relatório, licenciamento comercial, avaliação privada, SDK/API, SLA ou treino personalizado, contacte a InsightFace: https://www.insightface.ai/contact",
        "generated_by": "Gerado por InsightFace Evaluation Studio",
    },
    "ru": {
        "title": "Корпоративный отчёт оценки InsightFace",
        "local_notice": "Вся обработка выполняется локально. Изображения, эмбеддинги и отчёты не загружаются автоматически.",
        "executive_summary": "Резюме",
        "evaluation_scenario": "Сценарий оценки",
        "dataset_summary": "Сводка датасета",
        "model_runtime": "Модель и среда выполнения",
        "license_status": "Статус лицензии",
        "metrics": "Метрики",
        "threshold_recommendation": "Рекомендация порога",
        "error_analysis": "Анализ ошибок",
        "latency_hardware": "Задержка и оборудование",
        "deployment_considerations": "Рекомендации по внедрению",
        "responsible_use": "Ответственное использование и соответствие требованиям",
        "commercial_next_steps": "Следующие шаги коммерческого лицензирования",
        "appendix_raw": "Приложение: сырые результаты",
        "scenario": "Сценарий",
        "created_at": "Создано",
        "license": "Лицензия",
        "model": "Модель",
        "provider": "Провайдер",
        "threshold": "Порог",
        "field": "Поле",
        "value": "Значение",
        "metric": "Метрика",
        "not_available": "Недоступно",
        "no_errors": "Случаи ошибок не зафиксированы.",
        "raw_note": "Показаны первые {count} строк сырых результатов.",
        "commercial_notice": "Эта оценка может использовать исследовательские или некоммерческие файлы моделей. Производственное или коммерческое внедрение требует соответствующей коммерческой лицензии модели.",
        "responsible_notice": "Пользователи отвечают за согласие, конфиденциальность, хранение и соблюдение применимых биометрических норм.",
        "legal_notice": "Этот отчёт не является юридической консультацией.",
        "contact_notice": "Для разбора отчета, коммерческого лицензирования модели, приватной оценки, доступа к SDK/API, SLA или индивидуального обучения свяжитесь с InsightFace: https://www.insightface.ai/contact",
        "generated_by": "Создано InsightFace Evaluation Studio",
    },
}


def _rt(key: str, language: str | None = None) -> str:
    lang = effective_language(language)
    return _REPORT_TRANSLATIONS.get(lang, _REPORT_TRANSLATIONS["en"]).get(
        key, _REPORT_TRANSLATIONS["en"].get(key, key)
    )


def _value_to_text(value: Any) -> str:
    if value is None:
        return ""
    if isinstance(value, float):
        return f"{value:.6f}"
    if isinstance(value, (dict, list, tuple)):
        return safe_json_dumps(value)
    return str(value)


def _metric_lines(metrics: Dict[str, Any]) -> Iterable[str]:
    for key, value in metrics.items():
        yield f"- **{key}**: {_value_to_text(value)}"


def _markdown_escape(value: Any) -> str:
    return _value_to_text(value).replace("|", "\\|").replace("\n", "<br>")


def _markdown_table(rows: Sequence[Tuple[str, Any]], language: str | None = None) -> List[str]:
    lines = [
        f"| {_rt('field', language)} | {_rt('value', language)} |",
        "| --- | --- |",
    ]
    for key, value in rows:
        lines.append(f"| {_markdown_escape(key)} | {_markdown_escape(value)} |")
    return lines


def _summary_rows(result: EvaluationResult, language: str | None) -> List[Tuple[str, Any]]:
    threshold_recommendation = (
        f"{result.threshold_recommendation:.6f}"
        if result.threshold_recommendation is not None
        else _rt("not_available", language)
    )
    return [
        (_rt("scenario", language), result.scenario),
        (_rt("created_at", language), result.created_at),
        (_rt("model", language), result.model_name),
        (_rt("provider", language), result.provider),
        (_rt("license", language), result.license_status),
        (_rt("threshold_recommendation", language), threshold_recommendation),
    ]


def generate_markdown_report(result: EvaluationResult, language: str | None = None) -> str:
    raw_rows = result.raw_results[:50]
    raw_block = safe_json_dumps(raw_rows)
    lines = [
        f"# {_rt('title', language)}",
        "",
        f"> {_rt('local_notice', language)}",
        "",
        f"## 1. {_rt('executive_summary', language)}",
        *_markdown_table(_summary_rows(result, language), language),
        "",
        f"## 2. {_rt('evaluation_scenario', language)}",
        result.scenario,
        "",
        f"## 3. {_rt('dataset_summary', language)}",
        *_markdown_table(list(result.dataset_summary.items()), language),
        "",
        f"## 4. {_rt('model_runtime', language)}",
        *_markdown_table(
            [
                (_rt("model", language), result.model_name),
                (_rt("provider", language), result.provider),
                (_rt("threshold", language), f"{result.threshold:.6f}"),
            ],
            language,
        ),
        "",
        f"## 5. {_rt('license_status', language)}",
        result.license_status,
        "",
        f"## 6. {_rt('metrics', language)}",
        *list(_metric_lines(result.metrics)),
        "",
        f"## 7. {_rt('threshold_recommendation', language)}",
        _summary_rows(result, language)[-1][1],
        "",
        f"## 8. {_rt('error_analysis', language)}",
        safe_json_dumps(result.errors[:50]) if result.errors else _rt("no_errors", language),
        "",
        f"## 9. {_rt('latency_hardware', language)}",
        *_markdown_table(list(result.latency.items()), language),
        "",
        f"## 10. {_rt('deployment_considerations', language)}",
        _rt("commercial_notice", language),
        "",
        f"## 11. {_rt('responsible_use', language)}",
        _rt("responsible_notice", language),
        "",
        _rt("legal_notice", language),
        "",
        f"## 12. {_rt('commercial_next_steps', language)}",
        _rt("contact_notice", language),
        "",
        f"## 13. {_rt('appendix_raw', language)}",
        _rt("raw_note", language).format(count=len(raw_rows)),
        "",
        "```json",
        raw_block,
        "```",
        "",
    ]
    return "\n".join(str(line) for line in lines)


def generate_html_report(result: EvaluationResult, language: str | None = None) -> str:
    markdown = generate_markdown_report(result, language)
    lines = []
    in_code = False
    for line in markdown.splitlines():
        if line.startswith("```"):
            lines.append("</pre>" if in_code else "<pre>")
            in_code = not in_code
        elif in_code:
            lines.append(html.escape(line))
        elif line.startswith("# "):
            lines.append(f"<h1>{html.escape(line[2:])}</h1>")
        elif line.startswith("## "):
            lines.append(f"<h2>{html.escape(line[3:])}</h2>")
        elif line.startswith("> "):
            lines.append(f"<blockquote>{html.escape(line[2:])}</blockquote>")
        elif line.startswith("| "):
            lines.append(f"<p class='table-line'>{html.escape(line)}</p>")
        elif line.startswith("- "):
            lines.append(f"<p>{html.escape(line)}</p>")
        elif line.strip():
            lines.append(f"<p>{html.escape(line)}</p>")
        else:
            lines.append("")
    return (
        "<!doctype html><html><head><meta charset='utf-8'>"
        f"<title>{html.escape(_rt('title', language))}</title>"
        "<style>body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;"
        "max-width:1040px;margin:32px auto;line-height:1.55;color:#1f2937}"
        "h1{font-size:30px;color:#0f172a}h2{margin-top:28px;color:#1e3a8a}"
        "blockquote{background:#eaf3ff;border-left:4px solid #2563eb;padding:12px 16px}"
        "pre{background:#f3f4f6;padding:16px;overflow:auto;border-radius:8px}"
        ".table-line{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}</style></head><body>"
        + "\n".join(lines)
        + "</body></html>"
    )


def _candidate_font_paths() -> List[Path]:
    py_site = Path(sys.prefix) / "lib" / f"python{sys.version_info.major}.{sys.version_info.minor}" / "site-packages"
    win_site = Path(sys.prefix) / "Lib" / "site-packages"
    candidates = [
        py_site / "matplotlib" / "mpl-data" / "fonts" / "ttf" / "DejaVuSans.ttf",
        py_site / "matplotlib" / "mpl-data" / "fonts" / "ttf" / "DejaVuSans-Bold.ttf",
        win_site / "matplotlib" / "mpl-data" / "fonts" / "ttf" / "DejaVuSans.ttf",
        win_site / "matplotlib" / "mpl-data" / "fonts" / "ttf" / "DejaVuSans-Bold.ttf",
        Path("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"),
        Path("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"),
        Path("/usr/share/fonts/truetype/liberation2/LiberationSans-Regular.ttf"),
        Path("/usr/share/fonts/truetype/liberation2/LiberationSans-Bold.ttf"),
        Path("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"),
        Path("/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc"),
        Path("/Library/Fonts/Arial Unicode.ttf"),
        Path("/Library/Fonts/Arial.ttf"),
        Path("/System/Library/Fonts/Supplemental/Arial.ttf"),
        Path("/System/Library/Fonts/Supplemental/Arial Bold.ttf"),
        Path("C:/Windows/Fonts/arial.ttf"),
        Path("C:/Windows/Fonts/arialbd.ttf"),
        Path("C:/Windows/Fonts/segoeui.ttf"),
        Path("C:/Windows/Fonts/seguisb.ttf"),
    ]
    return [path for path in candidates if path.exists()]


def _register_pdf_fonts(language: str | None = None) -> Tuple[str, str]:
    from reportlab.pdfbase import pdfmetrics

    lang = effective_language(language)
    if lang in {"zh", "ja", "ko"}:
        from reportlab.pdfbase.cidfonts import UnicodeCIDFont

        cid_name = {"zh": "STSong-Light", "ja": "HeiseiMin-W3", "ko": "HYSMyeongJo-Medium"}[lang]
        try:
            pdfmetrics.registerFont(UnicodeCIDFont(cid_name))
            return cid_name, cid_name
        except Exception:
            pass

    regular_path = None
    bold_path = None
    for path in _candidate_font_paths():
        lower = path.name.lower()
        if regular_path is None and lower in {"dejavusans.ttf", "arial.ttf", "segoeui.ttf", "notosans-regular.ttf"}:
            regular_path = path
        if bold_path is None and lower in {"dejavusans-bold.ttf", "arialbd.ttf", "arial bold.ttf", "seguisb.ttf", "notosans-bold.ttf"}:
            bold_path = path
        if regular_path and bold_path:
            break

    if regular_path:
        try:
            from reportlab.pdfbase.ttfonts import TTFont

            pdfmetrics.registerFont(TTFont("InsightFaceReport", str(regular_path)))
            if bold_path:
                pdfmetrics.registerFont(TTFont("InsightFaceReportBold", str(bold_path)))
                return "InsightFaceReport", "InsightFaceReportBold"
            return "InsightFaceReport", "InsightFaceReport"
        except Exception:
            pass
    return "Helvetica", "Helvetica-Bold"


def _pdf_paragraph(text: Any, style):
    from reportlab.platypus import Paragraph

    escaped = html.escape(_value_to_text(text)).replace("\n", "<br/>")
    return Paragraph(escaped, style)


def _pdf_table(rows: Sequence[Tuple[Any, Any]], styles, language: str | None = None, widths=None):
    from reportlab.lib import colors
    from reportlab.platypus import Table, TableStyle

    data = [
        [
            _pdf_paragraph(_rt("field", language), styles["TableHeader"]),
            _pdf_paragraph(_rt("value", language), styles["TableHeader"]),
        ]
    ]
    for key, value in rows:
        data.append([_pdf_paragraph(key, styles["TableCellStrong"]), _pdf_paragraph(value, styles["TableCell"])])
    table = Table(data, colWidths=widths or [145, 340], repeatRows=1, hAlign="LEFT")
    table.setStyle(
        TableStyle(
            [
                ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#dbeafe")),
                ("TEXTCOLOR", (0, 0), (-1, 0), colors.HexColor("#0f172a")),
                ("GRID", (0, 0), (-1, -1), 0.35, colors.HexColor("#cbd5e1")),
                ("BACKGROUND", (0, 1), (-1, -1), colors.HexColor("#f8fafc")),
                ("VALIGN", (0, 0), (-1, -1), "TOP"),
                ("LEFTPADDING", (0, 0), (-1, -1), 8),
                ("RIGHTPADDING", (0, 0), (-1, -1), 8),
                ("TOPPADDING", (0, 0), (-1, -1), 6),
                ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
            ]
        )
    )
    return table


def _section(title: str, styles):
    from reportlab.platypus import Paragraph, Spacer

    return [Spacer(1, 14), Paragraph(html.escape(title), styles["SectionHeading"]), Spacer(1, 7)]


def write_pdf_report(result: EvaluationResult, path: str | Path, language: str | None = None) -> Path:
    from reportlab.lib import colors
    from reportlab.lib.enums import TA_CENTER
    from reportlab.lib.pagesizes import A4
    from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
    from reportlab.lib.units import mm
    from reportlab.platypus import SimpleDocTemplate, Spacer

    regular_font, bold_font = _register_pdf_fonts(language)
    root = Path(path)
    root.parent.mkdir(parents=True, exist_ok=True)

    base = getSampleStyleSheet()
    styles = {
        "Title": ParagraphStyle(
            "InsightFaceTitle",
            parent=base["Title"],
            fontName=bold_font,
            fontSize=24,
            leading=30,
            textColor=colors.HexColor("#0f172a"),
            alignment=TA_CENTER,
            spaceAfter=8,
        ),
        "Subtitle": ParagraphStyle(
            "InsightFaceSubtitle",
            parent=base["BodyText"],
            fontName=regular_font,
            fontSize=10.5,
            leading=14,
            textColor=colors.HexColor("#475569"),
            alignment=TA_CENTER,
        ),
        "Notice": ParagraphStyle(
            "InsightFaceNotice",
            parent=base["BodyText"],
            fontName=regular_font,
            fontSize=9.5,
            leading=13,
            textColor=colors.HexColor("#1e3a8a"),
            backColor=colors.HexColor("#eaf3ff"),
            borderColor=colors.HexColor("#93c5fd"),
            borderWidth=0.8,
            borderPadding=8,
            spaceAfter=8,
        ),
        "SectionHeading": ParagraphStyle(
            "InsightFaceSectionHeading",
            parent=base["Heading2"],
            fontName=bold_font,
            fontSize=14,
            leading=18,
            textColor=colors.HexColor("#1e3a8a"),
            spaceBefore=6,
            spaceAfter=4,
        ),
        "Body": ParagraphStyle(
            "InsightFaceBody",
            parent=base["BodyText"],
            fontName=regular_font,
            fontSize=9.5,
            leading=13.5,
            textColor=colors.HexColor("#1f2937"),
        ),
        "TableHeader": ParagraphStyle(
            "InsightFaceTableHeader",
            parent=base["BodyText"],
            fontName=bold_font,
            fontSize=8.8,
            leading=11,
            textColor=colors.HexColor("#0f172a"),
        ),
        "TableCellStrong": ParagraphStyle(
            "InsightFaceTableCellStrong",
            parent=base["BodyText"],
            fontName=bold_font,
            fontSize=8.4,
            leading=10.5,
            textColor=colors.HexColor("#0f172a"),
        ),
        "TableCell": ParagraphStyle(
            "InsightFaceTableCell",
            parent=base["BodyText"],
            fontName=regular_font,
            fontSize=8.2,
            leading=10.5,
            textColor=colors.HexColor("#334155"),
        ),
    }

    story: List[Any] = [
        _pdf_paragraph(_rt("title", language), styles["Title"]),
        _pdf_paragraph(f"{result.scenario} · {result.created_at}", styles["Subtitle"]),
        Spacer(1, 8),
        _pdf_paragraph(_rt("local_notice", language), styles["Notice"]),
    ]
    story.extend(_section(f"1. {_rt('executive_summary', language)}", styles))
    story.append(_pdf_table(_summary_rows(result, language), styles, language))
    story.extend(_section(f"2. {_rt('dataset_summary', language)}", styles))
    story.append(_pdf_table(list(result.dataset_summary.items()), styles, language))
    story.extend(_section(f"3. {_rt('model_runtime', language)}", styles))
    story.append(
        _pdf_table(
            [
                (_rt("model", language), result.model_name),
                (_rt("provider", language), result.provider),
                (_rt("threshold", language), f"{result.threshold:.6f}"),
            ],
            styles,
            language,
        )
    )
    story.extend(_section(f"4. {_rt('metrics', language)}", styles))
    story.append(_pdf_table(list(result.metrics.items()), styles, language))
    story.extend(_section(f"5. {_rt('error_analysis', language)}", styles))
    story.append(
        _pdf_paragraph(
            safe_json_dumps(result.errors[:50]) if result.errors else _rt("no_errors", language),
            styles["Body"],
        )
    )
    story.extend(_section(f"6. {_rt('latency_hardware', language)}", styles))
    story.append(_pdf_table(list(result.latency.items()), styles, language))
    story.extend(_section(f"7. {_rt('deployment_considerations', language)}", styles))
    story.append(_pdf_paragraph(_rt("commercial_notice", language), styles["Body"]))
    story.extend(_section(f"8. {_rt('responsible_use', language)}", styles))
    story.append(_pdf_paragraph(_rt("responsible_notice", language), styles["Body"]))
    story.append(_pdf_paragraph(_rt("legal_notice", language), styles["Body"]))
    story.extend(_section(f"9. {_rt('commercial_next_steps', language)}", styles))
    story.append(_pdf_paragraph(_rt("contact_notice", language), styles["Body"]))
    raw_rows = result.raw_results[:30]
    story.extend(_section(f"10. {_rt('appendix_raw', language)}", styles))
    story.append(_pdf_paragraph(_rt("raw_note", language).format(count=len(raw_rows)), styles["Body"]))
    story.append(_pdf_paragraph(safe_json_dumps(raw_rows), styles["Body"]))

    def footer(canvas, doc):
        canvas.saveState()
        canvas.setFillColor(colors.HexColor("#64748b"))
        canvas.setFont(regular_font, 8)
        canvas.drawString(18 * mm, 12 * mm, _rt("generated_by", language))
        canvas.drawRightString(192 * mm, 12 * mm, str(doc.page))
        canvas.restoreState()

    doc = SimpleDocTemplate(
        str(root),
        pagesize=A4,
        rightMargin=18 * mm,
        leftMargin=18 * mm,
        topMargin=16 * mm,
        bottomMargin=18 * mm,
        title=_rt("title", language),
    )
    doc.build(story, onFirstPage=footer, onLaterPages=footer)
    return root


def write_reports(result: EvaluationResult, report_dir: str | Path, language: str | None = None) -> Dict[str, str]:
    root = Path(report_dir)
    root.mkdir(parents=True, exist_ok=True)
    stem = f"insightface_evaluation_{timestamp_for_filename()}"
    markdown_path = root / f"{stem}.md"
    html_path = root / f"{stem}.html"
    pdf_path = root / f"{stem}.pdf"
    markdown_path.write_text(generate_markdown_report(result, language), encoding="utf-8")
    html_path.write_text(generate_html_report(result, language), encoding="utf-8")
    paths = {"markdown": str(markdown_path), "html": str(html_path)}
    try:
        write_pdf_report(result, pdf_path, language)
        paths["pdf"] = str(pdf_path)
    except Exception:
        pass
    result.report_path = paths.get("pdf") or paths["markdown"]
    return paths
