"""Smoke tests for xc-dl — no pytest required.

Run against an installed wheel/sdist:
    uv run --isolated --no-project --with dist/*.whl tests/smoke_test.py
"""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

passed = 0
failed = 0


def check(name: str, condition: bool, detail: str = "") -> None:
    global passed, failed
    if condition:
        passed += 1
        print(f"  PASS  {name}")
    else:
        failed += 1
        msg = f"  FAIL  {name}"
        if detail:
            msg += f"  ({detail})"
        print(msg)


def main() -> None:
    global passed, failed

    # ── Import checks ──────────────────────────────────────────────────────

    print("Import checks")

    try:
        import xc_dl

        check("import xc_dl", True)
    except ImportError as e:
        check("import xc_dl", False, str(e))

    try:
        ver = xc_dl.__version__
        check("__version__ is str", isinstance(ver, str) and len(ver) > 0, repr(ver))
        check("__version__ is not fallback", ver != "0.0.0", repr(ver))
    except AttributeError:
        check("__version__ is str", False, "attribute missing")
        check("__version__ is not fallback", False, "attribute missing")

    # ── CLI entry point ────────────────────────────────────────────────────

    print("\nCLI entry point")

    for cmd_label, args in [
        ("xc-dl --version", [sys.executable, "-m", "xc_dl", "--version"]),
        ("xc-dl --help", [sys.executable, "-m", "xc_dl", "--help"]),
    ]:
        try:
            result = subprocess.run(args, capture_output=True, text=True, timeout=30)
            check(cmd_label, result.returncode == 0, f"rc={result.returncode}")
        except Exception as e:
            check(cmd_label, False, str(e))

    # ── Utility functions ──────────────────────────────────────────────────

    print("\nUtility functions")

    from xc_dl.utils import (
        build_filename,
        build_relative_dir,
        normalise_url,
        parse_duration,
        parse_size,
        sanitise_path_component,
    )

    # parse_size
    check("parse_size('1GB')", parse_size("1GB") == 1_000_000_000)
    check("parse_size('1GiB')", parse_size("1GiB") == 2**30)
    check("parse_size('500MB')", parse_size("500MB") == 500_000_000)

    # parse_duration
    check("parse_duration('2:30')", parse_duration("2:30") == 150.0)
    check("parse_duration('1:00:05')", parse_duration("1:00:05") == 3605.0)
    check("parse_duration('')", parse_duration("") == 0.0)

    # sanitise_path_component
    check(
        "sanitise_path_component",
        sanitise_path_component('foo/bar:baz?"qux') == "foo_bar_baz_qux",
    )
    check("sanitise_path_component empty", sanitise_path_component("???") == "unknown")

    # build_filename
    check(
        "build_filename",
        build_filename("123", "Parus", "major", "mp3") == "XC00000123_Parus_major.mp3",
    )

    # build_relative_dir
    check(
        "build_relative_dir",
        build_relative_dir("Paridae", "Parus", "major")
        == Path("Paridae/Parus/Parus_major"),
    )

    # normalise_url
    check(
        "normalise_url protocol-relative",
        normalise_url("//example.com/f") == "https://example.com/f",
    )
    check(
        "normalise_url absolute", normalise_url("https://x.com/f") == "https://x.com/f"
    )

    # ── Pydantic models ───────────────────────────────────────────────────

    print("\nPydantic models")

    from xc_dl.api.models import APIResponse, Recording

    rec = Recording(id="456", gen="Corvus", sp="corax")
    check("Recording.id", rec.id == "456")
    check("Recording.species_name", rec.species_name == "Corvus corax")
    check("Recording defaults", rec.cnt == "" and rec.also == [])

    resp = APIResponse(numRecordings="10", numSpecies="2", recordings=[rec])
    check("APIResponse.total_recordings", resp.total_recordings == 10)
    check("APIResponse.total_species", resp.total_species == 2)
    check("APIResponse.recordings", len(resp.recordings) == 1)

    # ── Summary ────────────────────────────────────────────────────────────

    print(f"\n{'='*40}")
    print(f"  {passed} passed, {failed} failed")
    print(f"{'='*40}")

    sys.exit(1 if failed else 0)


if __name__ == "__main__":
    main()
