from __future__ import annotations

from decimal import Decimal
from typing import Any

from market_api.db.sql import qualify_table, quote_identifier
from market_api.tender.common import (
    TenderAggregate,
    build_scope_filter,
    format_growth,
    format_yi_yuan,
    normalize_month,
)


class TenderOverallRepository:
    def __init__(self, conn: Any, schema: str):
        self.conn = conn
        self.schema = schema

    def aggregate(
        self,
        year: int,
        months: list[int],
        scope_filter: tuple[str, str] | None,
    ) -> TenderAggregate:
        if not months:
            raise ValueError("统计月份不能为空")

        month_placeholders = ", ".join(["%s"] * len(months))
        where_parts = [
            f"{quote_identifier('年份')} = %s",
            f"{quote_identifier('月份')} IN ({month_placeholders})",
        ]
        params: list[object] = [year, *[f"{month}月" for month in months]]

        if scope_filter is not None:
            column_name, scope_value = scope_filter
            where_parts.append(f"{quote_identifier(column_name)} = %s")
            params.append(scope_value)

        sql = (
            "SELECT COUNT(*) AS tender_count, "
            f"COALESCE(SUM({quote_identifier('预算金额_万元')}), 0) AS amount_wan "
            f"FROM {qualify_table(self.schema, '公开市场招标数据')} "
            f"WHERE {' AND '.join(where_parts)}"
        )

        with self.conn.cursor() as cursor:
            cursor.execute(sql, params)
            row = cursor.fetchone()

        if row is None:
            return TenderAggregate(0, Decimal("0"))
        count, amount_wan = row
        return TenderAggregate(int(count or 0), Decimal(str(amount_wan or 0)))

def build_overall_summary(
    repository: object,
    year: int,
    month: str | int,
    scope: str,
    scope_value: str | None,
) -> dict[str, object]:
    month_number = normalize_month(month)
    normalized_scope_value = scope_value.strip() if scope_value is not None else None
    scope_filter = build_scope_filter(scope, normalized_scope_value)

    cumulative_months = list(range(1, month_number + 1))
    current_cumulative = repository.aggregate(year, cumulative_months, scope_filter)
    baseline_cumulative = repository.aggregate(year - 1, cumulative_months, scope_filter)
    current_monthly = repository.aggregate(year, [month_number], scope_filter)

    if month_number == 1:
        count_monthly_growth = "/"
        amount_monthly_growth = "/"
    else:
        previous_monthly = repository.aggregate(year, [month_number - 1], scope_filter)
        count_monthly_growth = format_growth(current_monthly.count, previous_monthly.count)
        amount_monthly_growth = format_growth(
            current_monthly.amount_wan,
            previous_monthly.amount_wan,
        )

    return {
        "统计年份": year,
        "统计月份": f"{month_number}月",
        "统计方式": scope,
        "统计参数": normalized_scope_value if scope != "上海" else None,
        "累计数据": {
            "招标次数": current_cumulative.count,
            "招标预算金额（亿元）": format_yi_yuan(current_cumulative.amount_wan),
            "招标次数同比增幅": format_growth(
                current_cumulative.count,
                baseline_cumulative.count,
            ),
            "招标金额同比增幅": format_growth(
                current_cumulative.amount_wan,
                baseline_cumulative.amount_wan,
            ),
        },
        "月度数据": {
            "招标次数": current_monthly.count,
            "招标预算金额（亿元）": format_yi_yuan(current_monthly.amount_wan),
            "招标次数环比增幅": count_monthly_growth,
            "招标金额环比增幅": amount_monthly_growth,
        },
    }
