#!/usr/bin/env python3
"""Internal Condensation client. Credentials stay in the local user config directory."""
import argparse
import json
import os
from pathlib import Path
import sys
import urllib.error
import urllib.request


def main():
    parser = argparse.ArgumentParser(description="Condensation internal sandbox service")
    commands = parser.add_subparsers(dest="command", required=True)
    commands.add_parser("status", help="Read live fleet health")
    listing = commands.add_parser("list", help="List fleet resources")
    listing.add_argument("kind", choices=["accounts", "apps", "agents"])
    api = commands.add_parser("api", help="Call a fleet endpoint; DELETE destroys the selected VM")
    api.add_argument("method", choices=["GET", "POST", "DELETE"])
    api.add_argument("path")
    api.add_argument("--body-file", help="JSON request file; use - for stdin")
    args = parser.parse_args()
    path = Path.home() / ".config/condensation/operator.json"
    config = json.loads(path.read_text()) if path.exists() else {}
    token = os.environ.get("CONDENSATION_TOKEN") or config.get("token")
    origin = os.environ.get("CONDENSATION_URL") or config.get("url")
    if not token or not origin:
        parser.error("Set CONDENSATION_URL and CONDENSATION_TOKEN, or configure ~/.config/condensation/operator.json")
    method, route = "GET", "/healthz"
    if args.command == "list": route = "/v1/" + args.kind
    if args.command == "api": method, route = args.method, args.path
    if not route.startswith("/") or route.startswith("//") or "?" in route or "#" in route:
        parser.error("Use an absolute API path without queries or fragments")
    if not origin.startswith("https://"):
        parser.error("CONDENSATION_URL must use HTTPS")
    body = None
    if args.command == "api" and args.body_file:
        raw = sys.stdin.read() if args.body_file == "-" else Path(args.body_file).read_text()
        body = json.dumps(json.loads(raw)).encode()
    request = urllib.request.Request(origin.rstrip("/") + route, data=body, method=method,
        headers={"Authorization": "Bearer " + token, "Content-Type": "application/json", "User-Agent": "CondensationCLI/0.1"})
    class NoRedirect(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, *unused): return None
    try:
        with urllib.request.build_opener(NoRedirect()).open(request, timeout=130) as response:
            raw = response.read()
            print(json.dumps(json.loads(raw), indent=2) if raw else "Done")
    except urllib.error.HTTPError as error:
        print(f"Condensation HTTP {error.code}", file=sys.stderr)
        if method != "GET": print("Inspect inventory before retrying; the operation may have completed.", file=sys.stderr)
        return 1
    except (urllib.error.URLError, TimeoutError):
        print("Condensation could not be reached. Inspect inventory before retrying a mutation.", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
