import builtins
from datetime import datetime
from typing import List

from pydantic import BaseModel, Field

from app.models.mirrors import Origin


class BC2Alternative(BaseModel):
    proto: str
    type: str
    created_at: datetime
    updated_at: datetime
    url: str


class BC2Site(BaseModel):
    main_domain: str = Field(
        description="The main domain name of the website, excluding \"www.\" if present.",
        examples=["bbc.co.uk", "bbc.com", "guardianproject.info"]
    )
    available_alternatives: List[BC2Alternative]


class BypassCensorship2(BaseModel):
    version: str = Field(
        description="Version number of the Bypass Censorship Extension schema in use",
    )
    sites: List[BC2Site]

    class Config:
        title = "Bypass Censorship Version 2"


def mirror_sites():
    return {
        "version": "2.0",
        "sites": [{
            "main_domain": x.description[len("proxy:"):].replace("www.", "") if x.description.startswith(
                "proxy:") else x.domain_name.replace("www.", ""),
            "available_alternatives": [
                                          {
                                              "proto": "tor" if ".onion" in a.url else "https",
                                              "type": "eotk" if ".onion" in a.url else "mirror",
                                              "created_at": str(a.added),
                                              "updated_at": str(a.updated),
                                              "url": a.url
                                          } for a in x.mirrors if not a.deprecated and not a.destroyed
                                      ] + [
                                          {
                                              "proto": "https",
                                              "type": "mirror",
                                              "created_at": str(a.added),
                                              "updated_at": str(a.updated),
                                              "url": a.url
                                          } for a in x.proxies if
                                          a.url is not None and not a.deprecated and not a.destroyed and a.provider == "cloudfront"
                                      ]} for x in Origin.query.order_by(Origin.domain_name).all() if x.destroyed is None
        ]
    }


if getattr(builtins, "__sphinx_build__", False):
    schema = BypassCensorship2.schema_json()
