"""Startup flow — first-run checks for auth, telemetry, and version."""

from __future__ import annotations

import asyncio
import contextlib
from datetime import UTC, datetime, timedelta
from pathlib import Path

from ievo.core.global_config import get_config, set_config
from ievo.core.telemetry import init_sentry

_VERSION_CHECK_INTERVAL = timedelta(hours=24)


def check_version_notification(home: Path) -> None:
    """Check for a newer ievo version and print a notification if available.

    Uses a 24h cache to avoid hitting PyPI on every launch.
    Silent on failure — never blocks startup with errors.
    """
    from ievo.core.updater import fetch_latest_version, get_current_version
    from ievo.utils.console import info

    # Check cache freshness
    last_run = get_config(home, "version_check_last_run")
    cached_version = get_config(home, "version_check_result")

    cache_fresh = False
    if isinstance(last_run, str) and isinstance(cached_version, str):
        try:
            last_dt = datetime.fromisoformat(last_run)
            if datetime.now(tz=UTC) - last_dt < _VERSION_CHECK_INTERVAL:
                cache_fresh = True
        except (ValueError, TypeError):
            pass

    if not cache_fresh:
        # Fetch from PyPI
        try:
            latest = asyncio.run(fetch_latest_version())
        except Exception:
            return
        # Update cache
        set_config(home, "version_check_last_run", datetime.now(tz=UTC).isoformat())
        set_config(home, "version_check_result", latest)
        cached_version = latest

    # Compare versions
    try:
        from packaging.version import InvalidVersion, Version

        current = Version(get_current_version())
        latest_v = Version(str(cached_version))
        if latest_v > current:
            info(
                f"A new version of ievo is available: v{cached_version}."
                " Run [bold]'ievo update'[/bold] to upgrade."
            )
    except (InvalidVersion, TypeError):
        pass


def ensure_startup(home: Path) -> None:
    """Run first-time setup checks. Idempotent — skips already-configured steps.

    1. Claude auth check (if not configured)
    2. Telemetry opt-in (if not asked yet)
    3. Initialize Sentry (if enabled)
    4. Version check notification (cached, silent on failure)
    """
    # Claude auth
    if get_config(home, "claude_auth") is None:
        from ievo.core.claude_auth import prompt_claude_auth

        prompt_claude_auth(home)

    # Telemetry
    if get_config(home, "telemetry") is None:
        from ievo.core.telemetry import prompt_telemetry

        prompt_telemetry(home)

    # Initialize Sentry (no-op if disabled or already initialized)
    init_sentry(home)

    # Version check — last step, never blocks startup
    with contextlib.suppress(Exception):
        check_version_notification(home)
