"""Automated Open Government Data (OGD) fetcher for Swiss federal bulk releases.

Downloads official nationwide datasets from geo.admin.ch, bfs.admin.ch, and madd.bfs.admin.ch
with support for resumable streaming downloads, checksum/cache checks, and automatic archive extraction.
"""

from __future__ import annotations

import logging
import os
import shutil
import zipfile
from pathlib import Path
from typing import Any, Dict, List, Optional

import httpx
import yaml
from tqdm import tqdm

logger = logging.getLogger(__name__)


def load_config(config_path: Path | str = "config.default.yaml") -> Dict[str, Any]:
    """Load default or user-provided YAML configuration."""
    path = Path(config_path)
    if not path.is_file():
        raise FileNotFoundError(f"Configuration file not found: {path.resolve()}")
    with open(path, "r", encoding="utf-8") as f:
        return yaml.safe_load(f) or {}


def resolve_stac_latest_asset(collection_id: str, preferred_ext: str = ".gpkg") -> Optional[str]:
    """Dynamically discover the newest asset URL from geo.admin.ch STAC API."""
    stac_url = f"https://data.geo.admin.ch/api/stac/v0.9/collections/{collection_id}/items"
    headers = {"User-Agent": "SwissHousingPipeline/0.1.0"}
    try:
        with httpx.Client(timeout=15.0, headers=headers) as client:
            resp = client.get(stac_url)
            if resp.status_code != 200:
                logger.warning("STAC collection %s returned HTTP %d", collection_id, resp.status_code)
                return None
            data = resp.json()
            features = data.get("features", [])
            if not features:
                return None
            # Items are typically chronological; pick the last item
            latest_feature = features[-1]
            assets = latest_feature.get("assets", {})

            # Match preferred extension first
            for asset_key, asset_val in assets.items():
                href = asset_val.get("href", "")
                if preferred_ext in href:
                    return href

            # Fallback to any valid href
            for asset_key, asset_val in assets.items():
                href = asset_val.get("href", "")
                if href.endswith((".parquet", ".zip", ".gpkg", ".csv")):
                    return href
    except Exception as exc:
        logger.warning("Could not query STAC API for %s: %s", collection_id, exc)
    return None


def download_file(
    url: str,
    dest_path: Path,
    resume: bool = True,
    timeout: float = 120.0,
) -> Path:
    """Download a file with resumable streaming, cache check, and progress reporting."""
    dest_path.parent.mkdir(parents=True, exist_ok=True)
    temp_path = dest_path.with_suffix(dest_path.suffix + ".part")

    headers = {"User-Agent": "SwissHousingPipeline/0.1.0"}
    client_params: dict[str, Any] = {"follow_redirects": True, "timeout": timeout, "headers": headers}

    # Cache check: if destination file exists and is non-empty, test remote Content-Length
    if dest_path.exists() and dest_path.stat().st_size > 0:
        try:
            with httpx.Client(**client_params) as client:
                head_resp = client.head(url)
                if head_resp.status_code == 200:
                    remote_len = int(head_resp.headers.get("content-length", -1))
                    local_len = dest_path.stat().st_size
                    if remote_len > 0 and remote_len == local_len:
                        logger.info("Cached file matches remote size (%d bytes): %s", local_len, dest_path.name)
                        return dest_path
        except Exception:
            # If head check fails, assume cached file is valid
            logger.info("Using existing cached file: %s", dest_path)
            return dest_path

    # Resume check
    existing_bytes = 0
    if resume and temp_path.exists():
        existing_bytes = temp_path.stat().st_size

    download_headers = dict(headers)
    if existing_bytes > 0:
        download_headers["Range"] = f"bytes={existing_bytes}-"

    with httpx.Client(follow_redirects=True, timeout=timeout, headers=download_headers) as client:
        with client.stream("GET", url) as response:
            if response.status_code == 416:
                # Requested range not satisfiable -> start fresh
                temp_path.unlink(missing_ok=True)
                return download_file(url, dest_path, resume=False, timeout=timeout)

            response.raise_for_status()

            total_size: Optional[int] = None
            content_length = response.headers.get("content-length")
            if content_length:
                total_size = int(content_length) + (existing_bytes if response.status_code == 206 else 0)

            mode = "ab" if (response.status_code == 206 and existing_bytes > 0) else "wb"
            if mode == "wb":
                existing_bytes = 0

            with open(temp_path, mode) as f, tqdm(
                total=total_size,
                initial=existing_bytes,
                unit="B",
                unit_scale=True,
                unit_divisor=1024,
                desc=dest_path.name,
                leave=True,
            ) as bar:
                for chunk in response.iter_bytes(chunk_size=1024 * 64):
                    if chunk:
                        f.write(chunk)
                        bar.update(len(chunk))

    # Atomically replace final file
    temp_path.replace(dest_path)
    logger.info("Saved: %s (%d bytes)", dest_path, dest_path.stat().st_size)
    return dest_path


def extract_archive(archive_path: Path, target_dir: Path) -> List[Path]:
    """Safely extract or normalize downloaded archives into target_dir."""
    target_dir.mkdir(parents=True, exist_ok=True)
    extracted: List[Path] = []

    if not archive_path.is_file():
        raise FileNotFoundError(f"Archive not found: {archive_path}")

    # Inspect file header magic bytes to detect uncompressed formats delivered directly
    with open(archive_path, "rb") as f:
        magic = f.read(16)

    # SQLite 3 / GeoPackage file misnamed or delivered uncompressed
    if magic.startswith(b"SQLite format 3\x00"):
        logger.info("Detected uncompressed SQLite 3 / GeoPackage database: %s", archive_path.name)
        if archive_path.suffix.lower() == ".zip":
            base = archive_path.name[:-4]
            if not base.lower().endswith(".gpkg"):
                base = Path(base).stem + ".gpkg"
            gpkg_path = target_dir / base
            logger.info("Normalizing file extension: %s -> %s", archive_path.name, gpkg_path.name)
            archive_path.rename(gpkg_path)
            return [gpkg_path]
        return [archive_path]

    # Parquet file misnamed or delivered uncompressed
    if magic.startswith(b"PAR1"):
        logger.info("Detected uncompressed Parquet file: %s", archive_path.name)
        if archive_path.suffix.lower() == ".zip":
            base = archive_path.name[:-4]
            if not base.lower().endswith(".parquet"):
                base = Path(base).stem + ".parquet"
            parquet_path = target_dir / base
            logger.info("Normalizing file extension: %s -> %s", archive_path.name, parquet_path.name)
            archive_path.rename(parquet_path)
            return [parquet_path]
        return [archive_path]

    if archive_path.suffix.lower() == ".zip":
        if not zipfile.is_zipfile(archive_path):
            logger.warning("File %s has .zip extension but is not a valid zip archive; skipping extraction.", archive_path.name)
            return [archive_path]

        logger.info("Extracting %s -> %s", archive_path.name, target_dir)
        with zipfile.ZipFile(archive_path, "r") as zf:
            for member in zf.infolist():
                # Prevent directory traversal attacks
                extracted_path = target_dir / member.filename
                if not extracted_path.resolve().is_relative_to(target_dir.resolve()):
                    raise ValueError(f"Dangerous path in zip archive: {member.filename}")
                zf.extract(member, target_dir)
                if not member.is_dir():
                    extracted.append(extracted_path)
    return extracted


def fetch_dataset(
    dataset_key: str,
    config: Optional[Dict[str, Any]] = None,
    force: bool = False,
    dynamic_stac: bool = True,
) -> Path:
    """Fetch and optionally extract a specific official Swiss dataset."""
    cfg = config or load_config()
    datasets = cfg.get("datasets", {})
    if dataset_key not in datasets:
        raise KeyError(f"Dataset key '{dataset_key}' not found in configuration. Available: {list(datasets.keys())}")

    ds_info = datasets[dataset_key]
    url = ds_info["url"]
    stac_col = ds_info.get("stac_collection")

    # If dynamic STAC lookup is requested and collection exists, check for newer version
    if dynamic_stac and stac_col:
        latest_url = resolve_stac_latest_asset(stac_col)
        if latest_url:
            logger.info("[%s] Resolved latest STAC URL: %s", dataset_key, latest_url)
            url = latest_url

    target_dir = Path(ds_info.get("target_dir", f"data/raw/{dataset_key}"))
    target_dir.mkdir(parents=True, exist_ok=True)

    url_filename = Path(url.split("?")[0]).name
    configured_filename = ds_info.get("filename")

    # Preserve configured filename only if its suffix matches the URL's format
    if configured_filename:
        conf_suffix = "".join(Path(configured_filename).suffixes).lower()
        url_suffix = "".join(Path(url_filename).suffixes).lower()
        if conf_suffix == url_suffix:
            filename = configured_filename
        else:
            filename = url_filename
    else:
        filename = url_filename

    archive_path = target_dir / filename

    if force and archive_path.exists():
        archive_path.unlink()

    # Cache check: if counterpart dataset file already exists and is non-empty, use it
    if not force:
        # Check direct target file
        if archive_path.exists() and archive_path.stat().st_size > 0:
            if archive_path.suffix.lower() == ".zip":
                extracted = extract_archive(archive_path, target_dir)
                if extracted:
                    return extracted[0]
            return archive_path
        # Check for extracted/normalized files in target directory (.gpkg, .parquet, .csv)
        existing = [
            f for f in target_dir.glob("*")
            if f.is_file() and f.suffix.lower() in (".gpkg", ".parquet", ".csv", ".shp") and f.stat().st_size > 10_000
        ]
        if existing:
            logger.info("Using existing dataset in %s: %s", target_dir, existing[0].name)
            return existing[0]

    logger.info("Fetching [%s] from %s", dataset_key, url)
    downloaded_file = download_file(url, archive_path)

    # If it is an archive or misnamed format, extract / normalize
    if downloaded_file.suffix.lower() == ".zip":
        extracted = extract_archive(downloaded_file, target_dir)
        if extracted:
            return extracted[0]

    return downloaded_file


def fetch_all(
    config: Optional[Dict[str, Any]] = None,
    force: bool = False,
    dynamic_stac: bool = True,
) -> Dict[str, Path]:
    """Fetch all official federal datasets specified in configuration."""
    cfg = config or load_config()
    results: Dict[str, Path] = {}
    for key in cfg.get("datasets", {}).keys():
        try:
            results[key] = fetch_dataset(key, cfg, force=force, dynamic_stac=dynamic_stac)
        except Exception as exc:
            logger.error("Failed to fetch %s: %s", key, exc)
            raise
    return results
