"""OSS 路径工具。"""

from __future__ import annotations

import re
from pathlib import Path


class OssPathUtils:
    """统一生成 LeAudit 使用的 OSS object key。"""

    @staticmethod
    def BuildBusinessDocKey(
        Region: str,
        TypeCode: str,
        DocumentId: int,
        Version: str,
        FileRole: str,
        FileName: str,
        Year: int | None = None,
        Month: int | None = None,
    ) -> str:
        """生成业务文档 object key。"""
        Ext = Path(FileName).suffix or ""
        safe_stem = OssPathUtils.BuildSafeFileStem(FileName)
        year_prefix = f"{Year:04d}" if Year is not None else "unknown-year"
        month_prefix = f"{Month:02d}" if Month is not None else "unknown-month"
        return (
            f"bdocs/{Region}/{TypeCode}/{year_prefix}/{month_prefix}/"
            f"{DocumentId}/{Version}/{FileRole}__{safe_stem}{Ext}"
        )

    @staticmethod
    def BuildArtifactKey(
        Region: str,
        RunId: int,
        ArtifactType: str,
        Detail: str,
    ) -> str:
        """生成评查产物 object key。"""
        return f"artifacts/{Region}/{RunId}/{ArtifactType}/{Detail}"

    @staticmethod
    def BuildRuleYamlKey(RuleType: str, VersionNo: str, *, Region: str = "") -> str:
        """生成规则 YAML object key。Region 为空时省略前缀。"""
        prefix = f"{Region}/" if Region else ""
        return f"{prefix}rules/{RuleType}/{VersionNo}/rules.yaml"

    @staticmethod
    def BuildRuleValidationReportKey(RuleType: str, VersionNo: str, *, Region: str = "") -> str:
        """生成规则校验报告 object key。"""
        prefix = f"{Region}/" if Region else ""
        return f"{prefix}rules/{RuleType}/{VersionNo}/validation_report.json"

    @staticmethod
    def BuildSafeFileStem(FileName: str) -> str:
        """生成适合放进 object key 的可读文件名主体。"""
        stem = Path(FileName).stem.strip() or "upload"
        stem = re.sub(r"[\\/:*?\"<>|]+", "_", stem)
        stem = re.sub(r"\s+", "_", stem)
        stem = re.sub(r"_+", "_", stem).strip("_")
        return (stem or "upload")[:96]
