import html
import re
from pathlib import Path
from typing import List


class StaffCreditHtmlExportService:
    """将员工姓名和身份证导出为征信解析样本 HTML。"""

    def __init__(self, staff_identity_repository):
        self.staff_identity_repository = staff_identity_repository

    def export(self, output_dir: Path) -> List[Path]:
        output_path = Path(output_dir)
        output_path.mkdir(parents=True, exist_ok=True)
        self._clear_existing_html(output_path)

        staff_list = self.staff_identity_repository.select_active_staff_identities()
        generated_files: List[Path] = []
        for index, staff in enumerate(staff_list, start=1):
            filename = self._build_filename(index, staff["staff_name"], staff["staff_id_card"])
            file_path = output_path / filename
            file_path.write_text(
                self.build_html(staff["staff_name"], staff["staff_id_card"]),
                encoding="utf-8",
            )
            generated_files.append(file_path)
        return generated_files

    def _clear_existing_html(self, output_dir: Path) -> None:
        for html_file in output_dir.glob("*.html"):
            html_file.unlink()

    def _build_filename(self, index: int, staff_name: str, staff_id_card: str) -> str:
        safe_name = self._sanitize_filename(staff_name)
        return f"{index:04d}_{safe_name}_{staff_id_card[-4:]}.html"

    @staticmethod
    def _sanitize_filename(name: str) -> str:
        sanitized = re.sub(r'[\\/:*?"<>|]+', "_", name).strip()
        return sanitized or "unknown"

    @staticmethod
    def build_html(staff_name: str, staff_id_card: str) -> str:
        escaped_name = html.escape(staff_name, quote=True)
        escaped_id_card = html.escape(staff_id_card, quote=True)
        return f"""<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="ccdi-staff-name" content="{escaped_name}" />
    <meta name="ccdi-staff-id-card" content="{escaped_id_card}" />
    <title>征信解析员工样本</title>
  </head>
  <body>
    <main>
      <h1>征信解析员工样本</h1>
      <p>姓名：{escaped_name}</p>
      <p>身份证号：{escaped_id_card}</p>
    </main>
  </body>
</html>
"""
