# backend/app/plugins/advanced_stats/derive.py
"""派生指标：从既有字段倒推出订单表没有单独存的数字。"""
from __future__ import annotations

from decimal import Decimal
from typing import Iterable

# 与 pricing.py:506 的 points_discount = points_to_use / 100 保持一致
POINTS_PER_UNIT = Decimal("100")


def split_points_ledger(changes: Iterable[int]) -> tuple[int, int]:
    """把 member_points_ledger.change_amount 拆成 (赚取, 使用)。

    正数 = 获得，负数 = 消耗。used 返回正数便于直接展示。
    对应 ADV 的 Reward Points (earned) / (used) 两列。
    """
    earned = 0
    used = 0
    for c in changes:
        if c > 0:
            earned += c
        else:
            used += -c
    return earned, used


def derive_coupon_total(*, discount_total: Decimal, points_used: int) -> Decimal:
    """倒推**该单所有券合计**抵扣了多少 = 折扣合计 - 积分抵扣额。

    名字里的 total 是字面意思：返回的是一单里所有券加起来的抵扣额，
    **不是单张券的**。想要单张券的精确金额，读 discount_usage_logs.discount_amount。

    口径分工（两条路不要混）：
    - 订单级维度（summary / country / payment_method …）：调本函数，从 orders
      表倒推，因为这些维度按订单聚合，拿不到单券粒度
    - coupon 维度：直接 SUM(discount_usage_logs.discount_amount)，精确到单张券，
      不调本函数

    依据：orders.discount_total = coupon_discount + points_discount
    （store/orders.py:319、orders.py:1010），且 points_discount = 积分 / POINTS_PER_UNIT。

    # ponytail: 前提是 discount_total 只含券 + 积分两项，且 100 积分 = 1 元
    # （pricing.py:506 硬编码）。若将来新增第三种折扣，这里会算错——那时应在
    # 下单时把各项折扣明细落进 extra_attributes，而不是继续加倒推分支。
    #
    # 上限：本函数只能得到"该单所有券合计抵扣多少"。一单叠加多张券时拆不到
    # 单张券——单张券的精确金额读 discount_usage_logs.discount_amount（Task 11
    # 起写入）；本函数仅用于该列为空的历史数据。
    """
    if points_used < 0:
        raise ValueError(f"points_used 必须非负，收到 {points_used}")
    points_amount = Decimal(points_used) / POINTS_PER_UNIT
    return max(Decimal("0"), Decimal(discount_total) - points_amount)
