#!/usr/bin/env python3
"""Push this repo's service descriptor to the relay.

Reads flydocs/context/service.json, strips the local-only `structure` section,
and pushes to PUT /api/relay/workspace/service.

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

import argparse
import json
import os
import sys
import urllib.error
import urllib.request
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="Push service descriptor to relay")
    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)")

    # Load service descriptor
    service_file = root / "flydocs" / "context" / "service.json"
    if not service_file.exists():
        fail("No service descriptor found at flydocs/context/service.json. Run flydocs init first.")

    descriptor = json.loads(service_file.read_text(encoding="utf-8"))

    # Strip local-only structure section before pushing
    export_descriptor = {k: v for k, v in descriptor.items() if k != "structure"}

    # Load config and credentials
    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.")

    repo_slug = config.get("repoSlug") or config.get("workspace", {}).get("repoSlug")
    if not repo_slug:
        repo_slug = descriptor.get("repoSlug")
    if not repo_slug:
        fail("repoSlug not found in config or service descriptor.")

    base_url = resolve_base_url(config)

    # Push descriptor
    url = f"{base_url}/workspace/service"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "X-Workspace": workspace_id,
        "X-Repo": repo_slug,
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    data = json.dumps({"descriptor": export_descriptor}).encode("utf-8")

    try:
        req = urllib.request.Request(url, data=data, headers=headers, method="PUT")
        with urllib.request.urlopen(req, timeout=15) as resp:
            result = json.loads(resp.read().decode("utf-8"))
            print(json.dumps({
                "success": True,
                "repoSlug": repo_slug,
                "fieldsExported": list(export_descriptor.keys()),
                "response": result,
            }, indent=2))
    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}")


if __name__ == "__main__":
    main()
