from __future__ import annotations

import json
from pathlib import Path
from typing import Any


class AuthorizedLinesMockService:
    """Mock da integração que informa quais linhas podem ser operadas.

    A linha digitada/falada pelo cliente nunca concede autorização. A consulta
    parte da identidade autenticada do atendimento e retorna somente linhas que
    um backend de identidade/conta teria previamente relacionado ao 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_linhas_autorizadas(
        self,
        *,
        authenticated_msisdn: str,
        customer_key: str | None = None,
        contract_key: str | None = None,
    ) -> dict[str, Any]:
        authenticated = self._digits(authenticated_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
            fixture_msisdn = self._digits(candidate.get("authenticated_msisdn"))
            if authenticated and fixture_msisdn == authenticated:
                account = candidate
                break

        if account is None:
            return {
                "success": False,
                "status": "AUTHORIZED_LINES_NOT_FOUND",
                "source": "mock",
                "authenticated_msisdn": authenticated,
                "authorized_lines": [],
                "authorized_msisdns": [authenticated] if authenticated else [],
                "reason": "authenticated_line_not_found_in_mock",
                "metadata": {"side_effect_free": True, "fixture": self.fixture_path.name},
            }

        rows: list[dict[str, Any]] = []
        seen: set[str] = set()
        for item in account.get("authorized_lines") or []:
            if not isinstance(item, dict):
                continue
            msisdn = self._digits(item.get("msisdn"))
            if not msisdn or msisdn in seen:
                continue
            seen.add(msisdn)
            row = dict(item)
            row["msisdn"] = msisdn
            rows.append(row)

        if authenticated and authenticated not in seen:
            rows.insert(0, {
                "msisdn": authenticated,
                "relationship": "authenticated",
                "status": "ACTIVE",
                "authorized": True,
            })

        authorized = [
            row["msisdn"]
            for row in rows
            if row.get("authorized", True) is True
            and str(row.get("status") or "ACTIVE").upper() == "ACTIVE"
        ]
        return {
            "success": True,
            "status": "SUCCESS",
            "source": "mock",
            "authenticated_msisdn": authenticated,
            "customer_key": customer_key or account.get("customer_key"),
            "contract_key": contract_key or account.get("contract_key"),
            "authorized_lines": rows,
            "authorized_msisdns": authorized,
            "metadata": {"side_effect_free": True, "fixture": self.fixture_path.name},
        }
