from __future__ import annotations

import json
from pathlib import Path
from typing import Any


class DiscountHistoryMockService:
    """Mock do sistema de registro/histórico de descontos do cliente.

    O serviço retorna fatos estruturados. A camada conversacional é responsável
    por transformar esses fatos em linguagem natural; o mock não devolve texto
    pronto para o cliente.
    """

    def __init__(self, fixture_path: Path) -> None:
        self.fixture_path = Path(fixture_path)

    @staticmethod
    def _digits(value: Any) -> str:
        return "".join(ch for ch in str(value or "") if ch.isdigit())

    def _load(self) -> dict[str, Any]:
        with self.fixture_path.open("r", encoding="utf-8") as fh:
            payload = json.load(fh)
        return payload if isinstance(payload, dict) else {}

    def consultar_historico_descontos(
        self,
        *,
        msisdn: str,
        customer_key: str | None = None,
        contract_key: str | None = None,
        nome_plano: str | None = None,
    ) -> dict[str, Any]:
        line = self._digits(msisdn)
        payload = self._load()
        accounts = payload.get("accounts") if isinstance(payload.get("accounts"), list) else []

        account: dict[str, Any] | None = None
        for candidate in accounts:
            if not isinstance(candidate, dict):
                continue
            if self._digits(candidate.get("msisdn")) == line:
                account = candidate
                break

        if account is None:
            return {
                "success": False,
                "status": "DISCOUNT_HISTORY_NOT_FOUND",
                "source": "mock",
                "msisdn": line,
                "discounts": [],
                "metadata": {"side_effect_free": True, "fixture": self.fixture_path.name},
            }

        requested_plan = str(nome_plano or "").strip().casefold()
        discounts: list[dict[str, Any]] = []
        for item in account.get("discounts") or []:
            if not isinstance(item, dict):
                continue
            plan_name = str(item.get("plan_name") or "").strip()
            if requested_plan and requested_plan not in plan_name.casefold():
                continue
            discounts.append(dict(item))

        return {
            "success": True,
            "status": "SUCCESS",
            "source": "mock",
            "msisdn": line,
            "customer_key": customer_key or account.get("customer_key"),
            "contract_key": contract_key or account.get("contract_key"),
            "as_of_date": account.get("as_of_date"),
            "last_invoice_issue_date": account.get("last_invoice_issue_date"),
            "last_billed_period": account.get("last_billed_period"),
            "discounts": discounts,
            "metadata": {
                "side_effect_free": True,
                "fixture": self.fixture_path.name,
                "authoritative_for": [
                    "discount_status",
                    "termination_reason",
                    "discount_dates",
                    "discount_values",
                    "contract_as_of_date",
                    "last_billed_discount_reference",
                ],
                "temporal_semantics": {
                    "current_value": "contract_value_as_of_date",
                    "last_billed_discount_value": "discount_applied_in_last_billed_period",
                },
            },
        }
