#!/usr/bin/env python3
"""
Standalone CLI for LinkedIn Recruiter bridge. Zero dependencies (stdlib only).

Install:
    pip install linkedin-bridge

Usage:
    linkedin-bridge parseCandidateList
    linkedin-bridge changeStage --stageName "Grade 5"
    linkedin-bridge navigateToUrl --url "https://www.linkedin.com/talent/hire/123/discover/pipeline"
    linkedin-bridge clickCandidateByIndex --index 3
"""

import json
import sys
import urllib.error
import urllib.request

API_BASE = "http://localhost:8321"


def http_get(url):
    try:
        with urllib.request.urlopen(url, timeout=5) as resp:
            return json.loads(resp.read())
    except urllib.error.URLError:
        print("ERROR: API not running at " + API_BASE, file=sys.stderr)
        sys.exit(1)


def http_post(url, body):
    data = json.dumps(body).encode()
    req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=35) as resp:
            return resp.status, json.loads(resp.read())
    except urllib.error.HTTPError as e:
        try:
            detail = json.loads(e.read()).get("detail", str(e))
        except Exception:
            detail = str(e)
        return e.code, {"detail": detail}
    except urllib.error.URLError:
        print("ERROR: Connection lost", file=sys.stderr)
        sys.exit(1)


def main():
    if len(sys.argv) < 2:
        print("Usage: linkedin-bridge <action> [--param value ...]", file=sys.stderr)
        sys.exit(1)

    action = sys.argv[1]

    # Parse --key value pairs
    params = {}
    args = sys.argv[2:]
    i = 0
    while i < len(args):
        if args[i].startswith("--"):
            key = args[i][2:]
            if i + 1 < len(args) and not args[i + 1].startswith("--"):
                val = args[i + 1]
                if val.isdigit():
                    val = int(val)
                elif val.lower() in ("true", "false"):
                    val = val.lower() == "true"
                params[key] = val
                i += 2
            else:
                params[key] = True
                i += 1
        else:
            i += 1

    # Get session
    status = http_get(f"{API_BASE}/api/bridge/status")
    if not status.get("connected") or not status.get("session_id"):
        print("ERROR: Bridge not connected", file=sys.stderr)
        sys.exit(1)

    session_id = status["session_id"]

    # Execute
    code, data = http_post(
        f"{API_BASE}/api/bridge/{session_id}/execute",
        {"action": action, "params": params, "timeout": 30},
    )

    if code != 200:
        print(f"ERROR: {data.get('detail', data)}", file=sys.stderr)
        sys.exit(1)

    print(json.dumps(data.get("result", data), indent=2, ensure_ascii=False))


if __name__ == "__main__":
    sys.exit(main())
