from __future__ import annotations

import re
from dataclasses import dataclass

from ..core.logger import AppLogger
from ..database.orm import SalaryRecordORM
from ..repositories import ReportRepository

logger = AppLogger.get_logger(__name__)
MONTH_RE = re.compile(r"^\d{4}-\d{2}$")


@dataclass(frozen=True)
class PayrollReport:
    salary_month: str | None
    totals: dict[str, float]
    attendance: dict[str, float]
    departments: list[dict[str, float | str]]
    recent_records: list[SalaryRecordORM]


class ReportService:
    """报表服务：提供薪资、考勤和部门维度的聚合结果。"""

    def __init__(self, repository: ReportRepository):
        self.repository = repository

    def payroll_summary(self, *, salary_month: str | None = None) -> PayrollReport:
        month = _clean_optional(salary_month)
        if month and not MONTH_RE.match(month):
            raise ValueError("工资月份格式必须为YYYY-MM")
        report = PayrollReport(
            salary_month=month,
            totals=self.repository.payroll_totals(salary_month=month),
            attendance=self.repository.attendance_totals(salary_month=month),
            departments=self.repository.department_totals(salary_month=month),
            recent_records=self.repository.recent_salary_records(salary_month=month),
        )
        logger.info("查询工资统计报表成功 salary_month=%s employee_count=%s", month, report.totals["employee_count"])
        return report


def _clean_optional(value: str | None) -> str | None:
    if value is None:
        return None
    stripped = value.strip()
    return stripped or None
