import requests
from datetime import datetime, timezone, timedelta
import threading

# Estado global (equivalente al objeto JS)
_updating_lock = threading.Lock()
_current_week = ""
_current_manifest = {"v": "2.0.0"}


def get_week_version():
    now = datetime.now(timezone.utc)

    # ISO: mover al jueves
    day = now.isoweekday()  # 1 (lunes) - 7 (domingo)
    thursday = now + timedelta(days=(4 - day))

    year = thursday.year

    year_start = datetime(year, 1, 1, tzinfo=timezone.utc)

    week = ((thursday - year_start).days + 1 + 6) // 7

    week_str = str(week).zfill(2)

    return f"{week_str}-{year}"


def verify(data=None, check_level=5):
    global _current_week, _current_manifest

    if data is None:
        data = {}

    # Normalizar check_level
    try:
        check_level = int(check_level)
    except:
        check_level = 5

    if check_level < 1:
        check_level = 1

    # Validaciones básicas
    if not data.get("prov_id"):
        return [False, "prov_id"]

    if not data.get("city_id") and check_level >= 2:
        return [False, "city_id"]

    if not data.get("street_id") and check_level >= 3:
        return [False, "street_id"]

    try:
        int(data.get("number"))
    except:
        if check_level >= 4:
            return [False, "number"]

    if not data.get("floor") and check_level >= 5:
        return [False, "floor"]

    v = _current_manifest.get("v")
    week_version = get_week_version()

    # Control de actualización (equivalente a Promise compartida)
    if not v or week_version != _current_week:
        with _updating_lock:
            # Double-check (importante en multithread)
            if not _current_manifest.get("v") or week_version != _current_week:
                try:
                    res = requests.get(
                        f"https://cdn.jsdelivr.net/gh/santiagomirantes/localiz.ar-db/manifest.json?weekVersion={week_version}",
                        timeout=5
                    )
                    manifest = res.json()

                    _current_week = week_version
                    _current_manifest = manifest

                except:
                    return [False, "internal"]

        v = _current_manifest.get("v")

    # Construir URL
    if check_level == 1:
        check_url = f"https://cdn.jsdelivr.net/gh/santiagomirantes/localiz.ar-db@{v}/dataset/{data.get('prov_id')}/ciudades.json"
        check_field = "prov_id"
    else:
        check_url = f"https://cdn.jsdelivr.net/gh/santiagomirantes/localiz.ar-db@{v}/dataset/{data.get('prov_id')}/{data.get('city_id')}/calles.json"
        check_field = "city_id"

    # Fetch dataset
    try:
        check_res = requests.get(check_url, timeout=5)
    except:
        return [False, "internal"]

    if check_res.status_code != 200:
        return [False, check_field]

    # Validación street_id
    if check_level >= 3:
        try:
            obj = check_res.json()
        except:
            return [False, "internal"]

        if f"_{data.get('street_id')}" not in obj:
            return [False, "street_id"]

    return [True, ""]