from __future__ import annotations

from dataclasses import dataclass
from decimal import Decimal, ROUND_HALF_UP


VALID_SCOPES = {"上海", "行政区", "属地"}
SCOPE_FILTER_COLUMNS = {
    "行政区": "归属区域_行政",
    "属地": "归属区域_属地",
}


@dataclass(frozen=True)
class TenderAggregate:
    count: int
    amount_wan: Decimal


def normalize_month(month: str | int) -> int:
    if isinstance(month, int):
        month_number = month
    else:
        raw_month = str(month).strip()
        if raw_month.endswith("月"):
            raw_month = raw_month[:-1]
        if not raw_month.isdecimal():
            raise ValueError("统计月份必须是 1-12 或 x月 格式")
        month_number = int(raw_month)

    if not 1 <= month_number <= 12:
        raise ValueError("统计月份必须在 1-12 之间")
    return month_number


def build_scope_filter(scope: str, scope_value: str | None) -> tuple[str, str] | None:
    normalized_value = scope_value.strip() if scope_value is not None else ""
    if scope not in VALID_SCOPES:
        raise ValueError("统计方式必须是 上海、行政区 或 属地")

    if scope == "上海":
        if normalized_value:
            raise ValueError("统计方式为上海时统计参数必须留空")
        return None

    if not normalized_value:
        raise ValueError(f"统计方式为{scope}时统计参数不能为空")
    return SCOPE_FILTER_COLUMNS[scope], normalized_value


def format_yi_yuan(amount_wan: Decimal | int | float | None) -> str:
    amount = Decimal("0") if amount_wan is None else Decimal(str(amount_wan))
    amount_yi = (amount / Decimal("10000")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    return f"{amount_yi:.2f}"


def format_growth(current: Decimal | int, baseline: Decimal | int) -> str:
    baseline_value = Decimal(str(baseline))
    if baseline_value == 0:
        return "/"
    current_value = Decimal(str(current))
    growth = ((current_value - baseline_value) / baseline_value * Decimal("100")).quantize(
        Decimal("0.01"),
        rounding=ROUND_HALF_UP,
    )
    return f"{growth:+.2f}"
