from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Dict
from urllib.request import Request, urlopen


def version_tuple(value: str) -> tuple[int, ...]:
    parts: list[int] = []
    for part in str(value or "0").replace("v", "").replace("V", "").split("."):
        try:
            parts.append(int("".join(ch for ch in part if ch.isdigit()) or "0"))
        except ValueError:
            parts.append(0)
    while len(parts) < 3:
        parts.append(0)
    return tuple(parts[:4])


def is_newer(latest: str, current: str) -> bool:
    return version_tuple(latest) > version_tuple(current)


def _read_update_payload(source: str) -> Dict[str, Any]:
    source = (source or "").strip()
    if not source:
        raise ValueError("Güncelleme kaynağı boş.")
    if source.lower().startswith(("http://", "https://")):
        req = Request(source, headers={"User-Agent": "TamerSEOAnalyzer-Updater/1.3"})
        with urlopen(req, timeout=10) as response:
            raw = response.read(1024 * 256)
            return json.loads(raw.decode("utf-8", errors="replace"))
    path = Path(source)
    if source.lower().startswith("file://"):
        path = Path(source[7:])
    if not path.exists():
        raise FileNotFoundError(f"Güncelleme dosyası bulunamadı: {path}")
    return json.loads(path.read_text(encoding="utf-8"))


def check_for_update(current_version: str, source: str) -> Dict[str, Any]:
    payload = _read_update_payload(source)
    latest = str(payload.get("latest_version") or payload.get("version") or current_version)
    return {
        "current_version": current_version,
        "latest_version": latest,
        "update_available": is_newer(latest, current_version),
        "download_url": payload.get("download_url", ""),
        "notes": payload.get("notes", ""),
        "published_at": payload.get("published_at", ""),
        "raw": payload,
    }
