"""Proxy domain models — Proxy server and proxy-account lease."""

from __future__ import annotations

import uuid
from datetime import datetime
from typing import Any, Literal

from repo_core.base.models import DomainModel


class Proxy(DomainModel):
    """Proxy server entity.

    Represents a proxy server with connection details, geolocation metadata,
    and performance metrics::

        proxy = Proxy.from_db({
            "id": "d-17432776848",
            "username": "jswfkloy",
            "password": "39llorwev9zk",
            "proxy_address": "212.212.18.77",
            "port": 6728,
            ...
        })
    """

    id: str
    username: str
    password: str
    proxy_address: str
    port: int
    valid: bool = True
    last_verification: datetime | None = None
    country_code: str | None = None
    city_name: str | None = None
    asn_name: str | None = None
    asn_number: int | None = None
    high_country_confidence: bool = True
    average_delay: float | None = None
    average_speed: float | None = None
    last_time_tested: datetime | None = None
    created_at: datetime | None = None
    updated_at: datetime | None = None


# ---------------------------------------------------------------------------
# Shared types
# ---------------------------------------------------------------------------

AccountType = Literal["telegram", "x", "instagram"]
LeaseMode = Literal["sticky", "timed"]


class ProxyLease(DomainModel):
    """Links a proxy server to a platform account via a lease.

    Polymorphic design — ``account_type`` discriminates which account table
    ``account_id`` references (``x_accounts``, ``telegram_accounts``, etc.).

    Lease modes
    -----------
    * **sticky** — permanent lease; the account keeps the proxy indefinitely.
    * **timed** — time-limited; the proxy is reclaimed after ``lease_duration_seconds``.

    A single proxy can be leased to multiple accounts (same or different
    platforms) concurrently.

    Example::

        {
            "id": "<uuid>",
            "proxy_id": "d-17432776848",
            "account_type": "x",
            "account_id": "<uuid-of-x-account>",
            "lease_mode": "timed",
            "lease_duration_seconds": 3600,
            "assigned_at": "2026-06-09T12:00:00Z",
            "is_active": true,
        }
    """

    id: uuid.UUID
    proxy_id: str
    account_type: AccountType
    account_id: uuid.UUID
    lease_mode: LeaseMode
    lease_duration_seconds: int | None = None
    assigned_at: datetime | None = None
    expires_at: datetime | None = None
    reclaimed_at: datetime | None = None
    is_active: bool = True
    created_at: datetime | None = None
    updated_at: datetime | None = None

