import json
import os
from pathlib import Path
from urllib.parse import urlsplit

import requests
from dotenv import load_dotenv


BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / ".env")

HTTP_TIMEOUT = int(os.getenv("HTTP_TIMEOUT", "600"))
FEED_CACHE_DIR = Path(os.getenv("FEED_CACHE_DIR", str(BASE_DIR / "feed_cache")))

FEED_CACHE_DIR.mkdir(parents=True, exist_ok=True)


def load_clients() -> list[dict]:
    clients_file = BASE_DIR / "clients.json"
    if not clients_file.exists():
        raise FileNotFoundError(f"Nem talalhato a clients.json: {clients_file}")

    with open(clients_file, "r", encoding="utf-8") as f:
        clients = json.load(f)

    if not isinstance(clients, list):
        raise ValueError("A clients.json gyokerelemenek listanak kell lennie.")

    return clients


def is_remote_url(url: str) -> bool:
    return (url or "").lower().startswith(("http://", "https://"))


def get_source_url(client: dict) -> str:
    source_url = (
        client.get("source_url")
        or client.get("feed_source_url")
        or client.get("download_url")
        or ""
    ).strip()

    feed_url = (client.get("feed_url") or "").strip()
    if not source_url and is_remote_url(feed_url):
        source_url = feed_url

    return source_url


def guess_extension(url: str, source_type: str) -> str:
    suffix = Path(urlsplit(url or "").path).suffix.lower().lstrip(".")
    if suffix in {"xml", "csv", "tsv", "txt"}:
        return suffix

    source_type = (source_type or "").strip().lower()
    if source_type == "tsv":
        return "tsv"
    if source_type in {"csv", "arukereso_csv"}:
        return "csv"
    if source_type in {"xml", "arukereso_xml"}:
        return "xml"

    return "dat"


def get_feed_cache_path(client: dict) -> Path:
    explicit_path = (client.get("local_feed_path") or "").strip()
    if explicit_path:
        return Path(explicit_path)

    filename = (
        client.get("feed_filename")
        or client.get("cache_filename")
        or ""
    ).strip()

    source_url = get_source_url(client)
    if not filename:
        filename = Path(urlsplit(source_url).path).name

    if not filename:
        name = (client.get("name") or "feed").strip() or "feed"
        ext = guess_extension(source_url, client.get("type", "xml"))
        filename = f"{name}.{ext}"

    path = FEED_CACHE_DIR / filename
    if not path.exists():
        single_cached_feed = find_single_cached_feed()
        if single_cached_feed:
            return single_cached_feed

    return path


def find_single_cached_feed() -> Path | None:
    feed_files = sorted(
        [
            path
            for pattern in ("*.xml", "*.csv", "*.tsv", "*.txt")
            for path in FEED_CACHE_DIR.glob(pattern)
        ],
        key=lambda path: path.stat().st_mtime,
        reverse=True,
    )

    return feed_files[0] if len(feed_files) == 1 else None


def download_feed(name: str, url: str, output_path: Path) -> dict:
    temp_path = output_path.with_suffix(output_path.suffix + ".tmp")
    output_path.parent.mkdir(parents=True, exist_ok=True)

    print(f"[{name}] letoltes indul")
    print(f"[{name}] cel: {output_path}")

    with requests.get(
        url,
        stream=True,
        timeout=(60, HTTP_TIMEOUT),
        headers={
            "User-Agent": "Mozilla/5.0 (compatible; FeedDownloader/1.0; +https://salesinnovo.com)"
        },
        allow_redirects=True,
    ) as response:
        print(f"[{name}] HTTP: {response.status_code}")
        print(f"[{name}] Content-Type: {response.headers.get('Content-Type')}")
        print(f"[{name}] Content-Length: {response.headers.get('Content-Length')}")

        response.raise_for_status()

        downloaded = 0
        with open(temp_path, "wb") as f:
            for chunk in response.iter_content(chunk_size=1024 * 1024):
                if not chunk:
                    continue

                f.write(chunk)
                downloaded += len(chunk)
                print(f"[{name}] letoltve: {downloaded / 1024 / 1024:.2f} MB", end="\r")

    temp_path.replace(output_path)

    print()
    print(f"[{name}] kesz: {output_path}")
    print(f"[{name}] meret: {output_path.stat().st_size / 1024 / 1024:.2f} MB")

    return {
        "client": name,
        "ok": True,
        "path": str(output_path),
        "bytes": output_path.stat().st_size,
        "error": "",
    }


def process_client(client: dict) -> dict:
    name = (client.get("name") or "unknown").strip()
    source_url = get_source_url(client)
    output_path = get_feed_cache_path(client)

    if not source_url:
        return {
            "client": name,
            "ok": True,
            "path": str(output_path),
            "bytes": output_path.stat().st_size if output_path.exists() else 0,
            "error": "nincs tavoli source_url/download_url, kihagyva",
        }

    if not is_remote_url(source_url):
        return {
            "client": name,
            "ok": True,
            "path": str(output_path),
            "bytes": output_path.stat().st_size if output_path.exists() else 0,
            "error": "source_url nem HTTP/HTTPS, kihagyva",
        }

    try:
        return download_feed(name, source_url, output_path)
    except Exception as e:
        return {
            "client": name,
            "ok": False,
            "path": str(output_path),
            "bytes": 0,
            "error": str(e),
        }


def main():
    print("==== FEED DOWNLOAD START ====")
    results = []

    for client in load_clients():
        result = process_client(client)
        results.append(result)
        status = "OK" if result["ok"] else "HIBA"
        print(f"[{result['client']}] {status} | {result['path']} | {result['error']}")

    print("==== FEED DOWNLOAD END ====")
    return results


if __name__ == "__main__":
    main()
