from dataclasses import dataclass
from pathlib import Path


@dataclass(frozen=True)
class CertificateTemplateDefinition:
    code: str
    name: str
    description: str
    asset_filename: str
    dynamic_fields: tuple[str, ...]
    status: str = "active"

    @property
    def asset_path(self) -> Path:
        return Path(__file__).resolve().parents[1] / "assets" / self.asset_filename

    def to_dict(self) -> dict[str, object]:
        return {
            "code": self.code,
            "name": self.name,
            "description": self.description,
            "dynamic_fields": list(self.dynamic_fields),
            "preview_url": f"/api/admin/certificate-templates/{self.code}/preview",
            "status": self.status,
        }


CLASSIC_TEMPLATE_CODE = "classic"
PRACTICE_CAMP_TEMPLATE_CODE = "practice-camp"

CERTIFICATE_TEMPLATES = {
    CLASSIC_TEMPLATE_CODE: CertificateTemplateDefinition(
        code=CLASSIC_TEMPLATE_CODE,
        name="经典结业证书",
        description="通用课程结业证书，正文包含课程名称、阶段、课程时间和发证日期。",
        asset_filename="certificate-template.png",
        dynamic_fields=("姓名", "课程名称", "阶段名称", "课程开始日期", "课程结束日期", "发证日期"),
    ),
    PRACTICE_CAMP_TEMPLATE_CODE: CertificateTemplateDefinition(
        code=PRACTICE_CAMP_TEMPLATE_CODE,
        name="实修大本营结业证书",
        description="人本智慧五个月线上实修大本营专用版，只填写姓名、课程开始日期、课程结束日期和发证日期。",
        asset_filename="certificate-template-practice-camp.png",
        dynamic_fields=("姓名", "课程开始日期", "课程结束日期", "发证日期"),
    ),
}


def list_certificate_templates() -> list[CertificateTemplateDefinition]:
    return list(CERTIFICATE_TEMPLATES.values())


def get_certificate_template(code: str | None) -> CertificateTemplateDefinition:
    normalized_code = (code or CLASSIC_TEMPLATE_CODE).strip().lower()
    template = CERTIFICATE_TEMPLATES.get(normalized_code)
    if not template or template.status != "active":
        raise ValueError(f"未知或已停用的证书模板：{normalized_code}")
    if not template.asset_path.exists():
        raise FileNotFoundError(f"证书模板图片不存在：{template.asset_filename}")
    return template
