#!/usr/bin/env python3
"""
AppWeaver update check utility.
Non-blocking, cached (24h) check against the npm registry for @bytestrone.ai/appweaver-cli.
Standard library only (urllib, json, os, sys, time).
"""

import sys
import os
import json
import time
import urllib.request
import urllib.error

DEFAULT_REGISTRY_URL = "https://registry.npmjs.org"
DEFAULT_INTERVAL_SECONDS = 86400  # 24 hours
TIMEOUT_SECONDS = 1.5


def _is_newer(latest: str, current: str) -> bool:
    def parse_parts(v: str):
        v = v.lstrip("v").split("-")[0].strip()
        parts = []
        for p in v.split("."):
            try:
                parts.append(int(p))
            except ValueError:
                parts.append(0)
        while len(parts) < 3:
            parts.append(0)
        return parts[:3]

    return parse_parts(latest) > parse_parts(current)


def _get_project_info(workspace_root: str):
    pkg_name = "@bytestrone.ai/appweaver-cli"
    version = "2.0.0"

    # 1. Try reading package.json if in CLI directory
    pkg_path = os.path.join(workspace_root, "package.json")
    if os.path.exists(pkg_path):
        try:
            with open(pkg_path, "r", encoding="utf-8") as fh:
                data = json.load(fh)
                pkg_name = data.get("name", pkg_name)
                version = data.get("version", version)
                return pkg_name, version
        except Exception:
            pass

    # 2. Try reading .install-receipt.json
    receipt_path = os.path.join(workspace_root, ".appweaver", ".install-receipt.json")
    if os.path.exists(receipt_path):
        try:
            with open(receipt_path, "r", encoding="utf-8") as fh:
                data = json.load(fh)
                v = data.get("appweaverVersion")
                if v:
                    version = v
        except Exception:
            pass

    return pkg_name, version


def check_update(workspace_root: str = ".", force: bool = False):
    if os.environ.get("AW_NO_UPDATE_NOTIFIER") in ("1", "true") or os.environ.get("CI") == "true":
        return None

    workspace_root = os.path.abspath(workspace_root)
    state_dir = os.path.join(workspace_root, ".appweaver", "orchestrator", ".state")
    cache_path = os.path.join(state_dir, "update-check.json")

    pkg_name, current_version = _get_project_info(workspace_root)
    registry_url = f"{DEFAULT_REGISTRY_URL}/{pkg_name}"

    interval_sec = DEFAULT_INTERVAL_SECONDS
    env_interval = os.environ.get("AW_UPDATE_CHECK_INTERVAL")
    if env_interval:
        try:
            interval_sec = int(env_interval) * 3600
        except ValueError:
            pass

    cached_data = None
    if not os.path.exists(cache_path):
        home_cache = os.path.join(os.path.expanduser("~"), ".appweaver", "update-check.json")
        if os.path.exists(home_cache):
            cache_path = home_cache

    if os.path.exists(cache_path):
        try:
            with open(cache_path, "r", encoding="utf-8") as fh:
                cached_data = json.load(fh)
        except Exception:
            cached_data = None

    now = time.time()

    # Use cache if fresh
    if not force and cached_data and (now - cached_data.get("lastChecked", 0) < interval_sec):
        latest = cached_data.get("latestVersion", current_version)
        return {
            "current": current_version,
            "latest": latest,
            "has_update": _is_newer(latest, current_version),
            "cached": True,
        }

    # Query registry with short timeout
    try:
        req = urllib.request.Request(
            registry_url,
            headers={"Accept": "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8"},
        )
        with urllib.request.urlopen(req, timeout=TIMEOUT_SECONDS) as resp:
            if resp.status == 200:
                payload = json.loads(resp.read().decode("utf-8"))
                latest = payload.get("dist-tags", {}).get("latest")
                if latest:
                    os.makedirs(state_dir, exist_ok=True)
                    with open(cache_path, "w", encoding="utf-8") as fh:
                        json.dump({"lastChecked": now, "latestVersion": latest}, fh, indent=2)

                    return {
                        "current": current_version,
                        "latest": latest,
                        "has_update": _is_newer(latest, current_version),
                        "cached": False,
                    }
    except Exception:
        # Fallback to cache on network failure / offline mode
        if cached_data:
            latest = cached_data.get("latestVersion", current_version)
            return {
                "current": current_version,
                "latest": latest,
                "has_update": _is_newer(latest, current_version),
                "cached": True,
            }

    return None


def format_notice(current: str, latest: str) -> str:
    return (
        f"\n💡 Note: AppWeaver v{latest} is available (project is on v{current}).\n"
        f"   Run `appweaver update` or type `/appweaver update` in chat to review updates.\n"
    )


def main():
    force = "--force" in sys.argv
    as_json = "--json" in sys.argv
    silent = "--silent" in sys.argv

    res = check_update(force=force)
    if not res:
        if as_json:
            print(json.dumps({"has_update": False}))
        return 0

    if as_json:
        print(json.dumps(res, indent=2))
        return 0

    if res.get("has_update") and not silent:
        sys.stderr.write(format_notice(res["current"], res["latest"]))

    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception:
        sys.exit(0)  # Always exit 0, never break caller
