import re
from dataclasses import dataclass, field
from datetime import datetime, timezone
from decimal import Decimal
from typing import Any, Dict, List, Optional


def _dec(value: Any) -> Optional[Decimal]:
    return None if value is None else value if isinstance(value, Decimal) else Decimal(str(value))


_ISO = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?$")


def _time(value: Optional[str]) -> Optional[datetime]:
    """Parses .NET's ISO 8601 (up to 7 fractional digits, 'Z' or an offset, or none = UTC)."""
    if not value:
        return None
    m = _ISO.match(value)
    if not m:
        return datetime.fromisoformat(value)
    base, fraction, zone = m.groups()
    text = base + ("." + (fraction + "000000")[:6] if fraction else "")
    if zone and zone != "Z":
        text += zone
    parsed = datetime.fromisoformat(text)
    return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)


@dataclass(frozen=True)
class Payment:
    """A payment (or a refund, ``type == "refund"``), as ``get_payment`` returns it."""

    id: str  # "tx_…": a random string, not a number
    type: str
    amount: Decimal
    currency: str
    status: str  # pending, completed or aborted
    description: str
    reference: Optional[str]
    payment_code: Optional[str]
    refunded: Decimal
    refundable: Decimal
    refund_of: Optional[str]
    subscription_id: Optional[str]
    raw: Dict[str, Any]
    # Every subscription this payment belongs to: the one it charged, or all those a checkout of several started.
    subscription_ids: List[str] = field(default_factory=list)

    @property
    def completed(self) -> bool:
        return self.status == "completed"

    @classmethod
    def from_json(cls, d: Dict[str, Any]) -> "Payment":
        return cls(id=d["id"], type=d.get("type", "payment"), amount=_dec(d["amount"]), currency=d["currency"],
                   status=d["status"], description=d.get("description") or "", reference=d.get("reference"),
                   payment_code=d.get("payment_code"), refunded=_dec(d.get("refunded", 0)),
                   refundable=_dec(d.get("refundable", 0)), refund_of=d.get("refund_of"),
                   subscription_id=d.get("subscription_id"), raw=d,
                   subscription_ids=list(d.get("subscription_ids")
                                         or ([d["subscription_id"]] if d.get("subscription_id") else [])))


@dataclass(frozen=True)
class PaymentCode:
    """A QR code for a pending payment: put ``url`` in a QR code, or show the ready-made SVG at ``qr_svg``."""

    code: str
    url: str
    qr_svg: str


@dataclass(frozen=True)
class Refund:
    id: str
    amount: Decimal
    currency: str
    reference: str
    reason: Optional[str]


@dataclass(frozen=True)
class RefundResult:
    refund: Refund
    payment: Payment  # the refunded payment, with updated ``refunded`` / ``refundable``


@dataclass(frozen=True)
class Subscription:
    id: str  # "sub_…": a random string, not a number
    status: str  # offered, active or canceled
    active_period: bool  # within a paid period: give access while this is true
    amount: Decimal
    currency: str
    interval: str  # day, week, month or year
    interval_count: int
    description: Optional[str]
    url: str
    qr_svg: str
    subscribed_at: Optional[datetime]
    subscribed_for_days: Optional[int]
    subscribed_for_seconds: Optional[int]
    canceled: bool
    canceled_at: Optional[datetime]
    canceled_by: Optional[str]  # customer, merchant, bank or schedule
    current_period_start: Optional[datetime]
    current_period_end: Optional[datetime]
    next_charge_at: Optional[datetime]
    ends_at: Optional[datetime]
    last_day: Optional[datetime]
    charges: int
    last_error: Optional[str]
    customer_name: Optional[str]
    raw: Dict[str, Any]

    @classmethod
    def from_json(cls, d: Dict[str, Any]) -> "Subscription":
        return cls(id=d["id"], status=d["status"], active_period=bool(d.get("active_period")), amount=_dec(d["amount"]),
                   currency=d["currency"], interval=d["interval"], interval_count=d.get("interval_count", 1),
                   description=d.get("description"), url=d["url"], qr_svg=d["qr_svg"],
                   subscribed_at=_time(d.get("subscribed_at")), subscribed_for_days=d.get("subscribed_for_days"),
                   subscribed_for_seconds=d.get("subscribed_for_seconds"), canceled=bool(d.get("canceled")),
                   canceled_at=_time(d.get("canceled_at")), canceled_by=d.get("canceled_by"),
                   current_period_start=_time(d.get("current_period_start")),
                   current_period_end=_time(d.get("current_period_end")),
                   next_charge_at=_time(d.get("next_charge_at")), ends_at=_time(d.get("ends_at")),
                   last_day=_time(d.get("last_day")), charges=d.get("charges") or 0, last_error=d.get("last_error"),
                   customer_name=(d.get("customer") or {}).get("name"), raw=d)


@dataclass(frozen=True)
class SubscriptionCheckout:
    """The first payment of a subscription: hand ``transaction_id`` to the pay button / hosted checkout."""

    transaction_id: str
    subscription: Subscription


@dataclass(frozen=True)
class SubscriptionsCheckout:
    """One first payment for several subscriptions: hand ``transaction_id`` to the pay button / hosted checkout.
    Paying it starts all of ``subscriptions`` (in the order you listed them)."""

    transaction_id: str
    subscriptions: List[Subscription]


@dataclass(frozen=True)
class Rate:
    to_rate: Decimal  # converts currency_from into currency_to
    from_rate: Decimal  # the other way


SubscriptionList = List[Subscription]
