from __future__ import annotations

import hashlib
import hmac
import json
import os
import re
import platform
import socket
import ssl
import threading
import time
import urllib.error
import urllib.request
import uuid
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Optional
from urllib.parse import urlparse


GRACE_SECONDS = 150  # sin contacto con el servidor antes de dar la sesión por perdida
RETRY_SECONDS = 15

# Verificación ECDSA P-256 sin dependencias. Solo maneja datos públicos: no necesita tiempo constante.
_P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF
_N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
_B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B
_G = (0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,
      0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5)


def _add(a, b):
    if a is None:
        return b
    if b is None:
        return a
    if a[0] == b[0]:
        if (a[1] + b[1]) % _P == 0:
            return None
        slope = (3 * a[0] * a[0] - 3) * pow(2 * a[1], -1, _P) % _P
    else:
        slope = (b[1] - a[1]) * pow(b[0] - a[0], -1, _P) % _P
    x = (slope * slope - a[0] - b[0]) % _P
    return x, (slope * (a[0] - x) - a[1]) % _P


def _mul(k, point):
    result = None
    while k:
        if k & 1:
            result = _add(result, point)
        point = _add(point, point)
        k >>= 1
    return result


def verify_p256(public_key_hex: str, message: bytes, signature_hex: str) -> bool:
    if not re.fullmatch(r"04[0-9a-fA-F]{128}", public_key_hex) or not re.fullmatch(r"[0-9a-fA-F]{128}", signature_hex or ""):
        return False
    point = (int(public_key_hex[2:66], 16), int(public_key_hex[66:], 16))
    if max(point) >= _P or (point[1] ** 2 - point[0] ** 3 + 3 * point[0] - _B) % _P:
        return False
    r, s = int(signature_hex[:64], 16), int(signature_hex[64:], 16)
    if not (0 < r < _N and 0 < s < _N):
        return False
    w = pow(s, -1, _N)
    z = int.from_bytes(hashlib.sha256(message).digest(), "big")
    total = _add(_mul(z * w % _N, _G), _mul(r * w % _N, point))
    return total is not None and total[0] % _N == r


@dataclass
class Result:
    ok: bool
    http_status: int = 0
    error_code: str = ""
    message: str = ""
    session_token: str = ""
    seconds_left: Optional[int] = None
    heartbeat_interval_seconds: int = 45
    variables: Dict[str, str] = field(default_factory=dict)
    value: Optional[str] = None
    raw_json: str = ""
    data: Dict[str, Any] = field(default_factory=dict)
    transient: bool = False


class Client:
    # app_secret acepta la clave pública del producto (04…, 130 caracteres; recomendada) o el secreto antiguo.
    def __init__(self, base_url: str, product_id: str, client_name: str, client_version: str, app_secret: str = ""):
        self.base_url = base_url.rstrip("/")
        parsed = urlparse(self.base_url)
        if parsed.scheme != "https" and parsed.hostname not in {"localhost", "127.0.0.1", "::1"}:
            raise ValueError("HTTP sin TLS solo está permitido para localhost")
        self.product_id = product_id
        is_public = bool(re.fullmatch(r"04[0-9a-fA-F]{128}", app_secret or ""))
        self.public_key = app_secret if is_public else ""
        self.app_secret = "" if is_public else (app_secret or "")
        self.client_name = client_name
        self.client_version = client_version
        self.hwid = self.generate_stable_hwid()
        self.hwid_previous = self._legacy_hwid()
        self.subscription: Dict[str, Any] = {}
        self._last_contact = 0.0
        self.session_token = ""
        self.heartbeat_interval_seconds = 45
        self.variables: Dict[str, str] = {}
        self._stop = threading.Event()
        self._thread: Optional[threading.Thread] = None

    # Solo el identificador del sistema: no cambia con la red, las actualizaciones ni el nombre del PC.
    @staticmethod
    def generate_stable_hwid() -> str:
        machine_id = ""
        if os.name == "nt":
            try:
                import winreg
                access = winreg.KEY_READ | winreg.KEY_WOW64_64KEY
                with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Cryptography", 0, access) as key:
                    machine_id = str(winreg.QueryValueEx(key, "MachineGuid")[0])
            except OSError:
                pass
        else:
            try:
                with open("/etc/machine-id", encoding="ascii") as handle:
                    machine_id = handle.read().strip()
            except OSError:
                pass
        if not machine_id:
            return Client._legacy_hwid()
        return hashlib.sha256(("nexo-python|" + machine_id).encode("utf-8")).hexdigest()

    # HWID de versiones anteriores: se envía para que el servidor lo sustituya sin perder el equipo vinculado.
    @staticmethod
    def _legacy_hwid() -> str:
        values = [platform.node(), platform.machine(), platform.processor(), str(uuid.getnode())]
        if os.name == "nt":
            try:
                import winreg
                with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Cryptography") as key:
                    values.append(str(winreg.QueryValueEx(key, "MachineGuid")[0]))
            except OSError:
                pass
        return hashlib.sha256("|".join(values).encode("utf-8")).hexdigest()

    # Handshake inicial: valida estado de aplicación, versión, hash y firma del servidor
    def init(self, program_hash: str = "") -> Result:
        payload: dict[str, Any] = {
            "productId": self.product_id,
            "client": self._client_info(),
        }
        if program_hash:
            payload["programHash"] = program_hash
        return self._post("/v1/auth/init", payload)

    # Modo 1: Autenticación directa solo con Key (tipo KeyAuth)
    def license(self, license_key: str) -> Result:
        result = self._post("/v1/auth/license", {
            "productId": self.product_id,
            "licenseKey": license_key,
            "hwid": self.hwid,
            "hwidPrevious": self.hwid_previous,
            "client": self._client_info(),
        })
        return self._start_session(result)

    # Modo 2: Registro con Usuario, Contraseña y Key
    def register(self, username: str, password: str, license_key: str) -> Result:
        result = self._post("/v1/auth/register-credentials", {
            "productId": self.product_id,
            "licenseKey": license_key,
            "username": username,
            "password": password,
            "hwid": self.hwid,
            "hwidPrevious": self.hwid_previous,
            "client": self._client_info(),
        })
        return self._start_session(result)

    # Modo 3: Login solo con Usuario y Contraseña
    def login(self, username: str, password: str, license_key: str = "") -> Result:
        payload = {
            "productId": self.product_id,
            "username": username,
            "password": password,
            "hwid": self.hwid,
            "hwidPrevious": self.hwid_previous,
            "client": self._client_info(),
        }
        if license_key:
            payload["licenseKey"] = license_key
        result = self._post("/v1/auth/login", payload)
        return self._start_session(result)

    # Modo 4: Canjear key para extender tiempo de usuario
    def upgrade(self, username: str, password: str, license_key: str) -> Result:
        return self._post("/v1/auth/upgrade", {
            "productId": self.product_id,
            "username": username,
            "password": password,
            "licenseKey": license_key,
        })

    def _start_session(self, result: Result) -> Result:
        if result.ok:
            self.session_token = result.session_token
            self.heartbeat_interval_seconds = max(15, result.heartbeat_interval_seconds)
            self.variables = result.variables
            self.subscription = result.data.get("subscription") or {}
            self._last_contact = time.monotonic()
        return result

    def change_password(self, username: str, password: str, new_password: str) -> Result:
        return self._post("/v1/auth/change-password", {
            "productId": self.product_id, "username": username, "password": password, "newPassword": new_password,
        })

    # Contraseña olvidada: pide la key y solo funciona en un equipo ya vinculado a la cuenta.
    def reset_password(self, username: str, license_key: str, new_password: str) -> Result:
        return self._post("/v1/auth/reset-password", {
            "productId": self.product_id, "username": username, "licenseKey": license_key, "newPassword": new_password,
            "hwid": self.hwid, "hwidPrevious": self.hwid_previous,
        })

    def _session(self, endpoint: str, payload: dict[str, Any]) -> Result:
        if not self.session_token:
            return Result(False, error_code="SESSION_REQUIRED", message="No hay una sesión iniciada")
        return self._post(endpoint, payload, authorized=True)

    # Variables propias de este cliente (se guardan en el servidor)
    def set_var(self, key: str, value: str) -> Result:
        return self._session("/v1/auth/setvar", {"key": key, "value": value})

    def get_user_var(self, key: str) -> Result:
        return self._session("/v1/auth/getvar", {"key": key})

    def online(self) -> Result:
        return self._session("/v1/auth/online", {})

    def chat_send(self, message: str, channel: str = "general") -> Result:
        return self._session("/v1/auth/chat/send", {"message": message, "channel": channel})

    def chat_fetch(self, after: int = 0, channel: str = "general") -> Result:
        return self._session("/v1/auth/chat/fetch", {"after": after, "channel": channel})

    def list_files(self) -> Result:
        return self._session("/v1/auth/files", {})

    # Descarga un archivo en "path" solo si su SHA-256 coincide con el que firmó el servidor.
    def download_file(self, file_id: str, path: str) -> Result:
        meta = self._session("/v1/auth/file", {"id": file_id})
        if not meta.ok:
            return meta
        external = bool(meta.data.get("external"))
        url = meta.data["url"] if external else self.base_url + meta.data["url"]
        headers = {"User-Agent": "NexoAuth-Python-SDK/3.0"}
        if not external:
            headers["Authorization"] = f"Bearer {self.session_token}"
        try:
            with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=300, context=ssl.create_default_context()) as response:
                content = response.read()
        except (urllib.error.URLError, TimeoutError, OSError) as error:
            return Result(False, error_code="DOWNLOAD_FAILED", message=str(error))
        if hashlib.sha256(content).hexdigest() != meta.data.get("sha256"):
            return Result(False, error_code="FILE_TAMPERED", message="El archivo descargado no coincide con el original")
        with open(path, "wb") as handle:
            handle.write(content)
        return meta

    def fetch_var(self, key: str) -> Result:
        if not self.session_token:
            return Result(False, error_code="SESSION_REQUIRED", message="No hay una sesión iniciada")
        return self._post("/v1/auth/var", {"key": key}, authorized=True)

    def log(self, message: str) -> Result:
        if not self.session_token:
            return Result(False, error_code="SESSION_REQUIRED", message="No hay una sesión iniciada")
        return self._post("/v1/auth/log", {"message": message, "pcName": socket.gethostname()}, authorized=True)

    def heartbeat(self) -> Result:
        if not self.session_token:
            return Result(False, error_code="SESSION_REQUIRED", message="No hay una sesión iniciada")
        result = self._post("/v1/auth/heartbeat", {}, authorized=True)
        if result.ok:
            self._last_contact = time.monotonic()
        # Un corte de red o del servidor no cierra la sesión hasta agotar el margen; un rechazo real, sí.
        elif not (result.transient and time.monotonic() - self._last_contact < GRACE_SECONDS):
            result.transient = False
            self.session_token = ""
        return result

    def logout(self) -> Result:
        self.stop_heartbeat()
        if not self.session_token:
            return Result(False, error_code="SESSION_REQUIRED", message="No hay una sesión iniciada")
        result = self._post("/v1/auth/logout", {}, authorized=True)
        self.session_token = ""
        return result

    def start_heartbeat(self, callback: Optional[Callable[[Result], None]] = None) -> None:
        self.stop_heartbeat()
        self._stop.clear()

        def loop() -> None:
            delay = self.heartbeat_interval_seconds
            while not self._stop.wait(delay):
                result = self.heartbeat()
                if result.transient:
                    delay = RETRY_SECONDS
                    continue
                if callback:
                    callback(result)
                if not result.ok:
                    break
                delay = self.heartbeat_interval_seconds = max(15, result.heartbeat_interval_seconds)

        self._thread = threading.Thread(target=loop, name="nexo-auth-heartbeat", daemon=True)
        self._thread.start()

    def stop_heartbeat(self) -> None:
        self._stop.set()
        if self._thread and self._thread.is_alive() and self._thread is not threading.current_thread():
            self._thread.join(timeout=2)
        self._thread = None

    def get_var(self, key: str, fallback: str = "") -> str:
        return self.variables.get(key, fallback)

    def _client_info(self) -> dict[str, str]:
        return {
            "name": self.client_name,
            "version": self.client_version,
            "platform": platform.system().lower(),
            "pcName": socket.gethostname(),
        }

    def _verify_signature(self, data: Any, signature: str) -> bool:
        if not self.app_secret:
            return True
        if not signature:
            return False
        hmac_key = hashlib.sha256(self.app_secret.encode("utf-8")).hexdigest().encode("utf-8")
        payload_bytes = json.dumps(data, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
        expected = hmac.new(hmac_key, payload_bytes, hashlib.sha256).hexdigest()
        return hmac.compare_digest(expected, signature)

    def _post(self, endpoint: str, payload: dict[str, Any], authorized: bool = False) -> Result:
        nonce = os.urandom(16).hex()
        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": "NexoAuth-Python-SDK/3.0",
            "x-nexo-nonce": nonce,
        }
        if authorized and self.session_token:
            headers["Authorization"] = f"Bearer {self.session_token}"
        request = urllib.request.Request(self.base_url + endpoint, json.dumps(payload).encode(), headers, method="POST")
        resp_sig = ""
        resp_sig_v2 = ""
        try:
            with urllib.request.urlopen(request, timeout=15, context=ssl.create_default_context()) as response:
                status, raw = response.status, response.read().decode("utf-8")
                resp_sig = response.headers.get("x-nexo-signature", "")
                resp_sig_v2 = response.headers.get("x-nexo-signature-v2", "")
        except urllib.error.HTTPError as error:
            status, raw = error.code, error.read().decode("utf-8", errors="replace")
            resp_sig_v2 = error.headers.get("x-nexo-signature-v2", "")
        except (urllib.error.URLError, TimeoutError, OSError) as error:
            return Result(False, error_code="NETWORK_ERROR", message=str(error), transient=True)
        # Se comprueba el texto tal como llegó. La firma cubre nonce, estado y cuerpo, también en errores.
        verified = not self.public_key or verify_p256(self.public_key, f"{nonce}.{status}.{raw}".encode("utf-8"), resp_sig_v2)
        if not verified and 200 <= status < 300:
            return Result(False, status, "INVALID_SIGNATURE", "Firma criptográfica del servidor inválida", raw_json=raw)
        try:
            document = json.loads(raw)
        except json.JSONDecodeError:
            return Result(False, status, "INVALID_RESPONSE", "El servidor devolvió una respuesta inválida", raw_json=raw, transient=True)
        data, error = document.get("data") or {}, document.get("error") or {}
        ok = 200 <= status < 300 and document.get("success") is True
        # Con firma activa el nonce es obligatorio: sin él se podría reutilizar una respuesta capturada.
        if ok and isinstance(data, dict) and (data.get("nonce") or self.app_secret) and not hmac.compare_digest(str(data.get("nonce")), nonce):
            return Result(False, status, "REPLAY_DETECTED", "Nonce de respuesta inválido", raw_json=raw)
        if ok and self.app_secret:
            sig = resp_sig or document.get("signature", "")
            if not self._verify_signature(data, sig):
                return Result(False, status, "INVALID_SIGNATURE", "Firma criptográfica del servidor inválida", raw_json=raw)
        interval = data.get("nextHeartbeatSeconds", data.get("heartbeatIntervalSeconds", 45))
        variables = data.get("variables") or {}
        return Result(ok, status, error.get("code", "" if ok else "HTTP_ERROR"), error.get("message", "" if ok else "Solicitud rechazada"), data.get("sessionToken", ""), data.get("secondsLeft"), int(interval), variables, data.get("value"), raw, data,
                      not ok and error.get("code") != "MAINTENANCE" and (status >= 500 or status == 429 or not verified))

    def __enter__(self) -> "Client":
        return self

    def __exit__(self, *_: object) -> None:
        self.stop_heartbeat()
