#!/usr/bin/env python3
"""Pull workspace service descriptors from the relay.

Fetches GET /api/relay/workspace/services and caches the composite
at .flydocs/cache/workspace-services.json for local use.

Usage:
    python3 .claude/skills/flydocs-workflow/scripts/pull_services.py [--root PATH]
"""

import argparse
import json
import os
import sys
import urllib.error
import urllib.request
from datetime import datetime, timezone
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from graph_utils import find_project_root, fail


def load_api_key(root):
    """Load FLYDOCS_API_KEY from environment or .env files."""
    if os.environ.get("FLYDOCS_API_KEY"):
        return os.environ["FLYDOCS_API_KEY"]
    for name in [".env.local", ".env"]:
        env_file = root / name
        if env_file.exists():
            with open(env_file, "r") as f:
                for line in f:
                    line = line.strip()
                    if line.startswith("#") or "=" not in line:
                        continue
                    k, _, v = line.partition("=")
                    if k.strip() == "FLYDOCS_API_KEY":
                        v = v.strip().strip("\"'")
                        return v if v else None
    return None


def load_config(root):
    """Load .flydocs/config.json."""
    config_path = root / ".flydocs" / "config.json"
    if config_path.exists():
        with open(config_path, "r") as f:
            return json.load(f)
    return {}


def resolve_base_url(config):
    """Resolve relay base URL."""
    env_url = os.environ.get("FLYDOCS_RELAY_URL")
    if env_url:
        return env_url.rstrip("/")
    config_url = config.get("relay", {}).get("url")
    if config_url:
        return config_url.rstrip("/")
    return "https://app.flydocs.ai/api/relay"


def main():
    parser = argparse.ArgumentParser(description="Pull workspace service descriptors")
    parser.add_argument("--root", type=str, default=None, help="Project root")
    args = parser.parse_args()

    root = Path(args.root) if args.root else find_project_root()
    if not root:
        fail("Could not find project root (no .flydocs/ directory found)")

    config = load_config(root)
    api_key = load_api_key(root)
    if not api_key:
        fail("FLYDOCS_API_KEY not found. Set in environment or .env file.")

    workspace_id = config.get("workspaceId")
    if not workspace_id:
        fail("workspaceId not found in .flydocs/config.json. Run flydocs init first.")

    base_url = resolve_base_url(config)

    # Fetch workspace services composite
    url = f"{base_url}/workspace/services"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "X-Workspace": workspace_id,
        "Accept": "application/json",
    }

    try:
        req = urllib.request.Request(url, headers=headers, method="GET")
        with urllib.request.urlopen(req, timeout=15) as resp:
            result = json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        error_body = e.read().decode("utf-8") if e.fp else ""
        try:
            error_data = json.loads(error_body) if error_body else {}
        except json.JSONDecodeError:
            error_data = {"error": error_body}
        fail(f"Relay API error ({e.code}): {error_data.get('error', str(e))}")
    except (urllib.error.URLError, TimeoutError) as e:
        fail(f"Network error: {e}")

    # Cache the composite locally
    cache_dir = root / ".flydocs" / "cache"
    cache_dir.mkdir(parents=True, exist_ok=True)
    cache_file = cache_dir / "workspace-services.json"

    cached = {
        "fetchedAt": datetime.now(timezone.utc).isoformat(),
        "services": result,
    }
    cache_file.write_text(json.dumps(cached, indent=2) + "\n", encoding="utf-8")

    # Report
    repos = result if isinstance(result, list) else result.get("repos", [])
    with_descriptor = sum(1 for r in repos if r.get("serviceDescriptor"))
    print(json.dumps({
        "success": True,
        "totalRepos": len(repos),
        "withDescriptor": with_descriptor,
        "cachedAt": cache_file.name,
    }, indent=2))


if __name__ == "__main__":
    main()
