from typing import List, Dict, Optional, TypedDict
from sqlalchemy.orm import selectinload

from app.models.base import Pool
from app.models.mirrors import Proxy


class RedirectorPool(TypedDict):
    short_name: str
    description: str
    api_key: str
    redirector_domain: Optional[str]
    origins: Dict[str, str]


class RedirectorData(TypedDict):
    version: str
    pools: List[RedirectorPool]


def redirector_pool_origins(pool: Pool) -> Dict[str, str]:
    return {
        proxy.origin.domain_name: proxy.url
        for proxy in Proxy.query.filter(
            Proxy.deprecated.is_(None),
            Proxy.destroyed.is_(None),
            Proxy.url.is_not(None),
            Proxy.pool_id == pool.id
        )
    }


def redirector_data(_: Optional[Pool]) -> RedirectorData:
    active_pools = Pool.query.options(
        selectinload(Pool.proxies)
    ).filter(Pool.destroyed.is_(None)).all()

    pools: List[RedirectorPool] = [
        {
            "short_name": pool.pool_name,
            "description": pool.description,
            "api_key": pool.api_key,
            "redirector_domain": pool.redirector_domain,
            "origins": redirector_pool_origins(pool)
        }
        for pool in active_pools
    ]

    return {
        "version": "1.0",
        "pools": pools
    }
