"""Shared utilities for peon-mcp Claude Code hooks."""

import json
import os
import subprocess
import urllib.error
import urllib.request


def get_api_url() -> str:
    """Get the peon REST API URL from environment."""
    return os.environ.get("PEON_API_URL", "http://127.0.0.1:8420").rstrip("/")


def get_api_key() -> str:
    """Get the peon API key from environment."""
    return os.environ.get("PEON_API_KEY", "")


def api_request(method: str, path: str, payload: dict | None = None, timeout: int = 5) -> dict | None:
    """Make a synchronous HTTP request to the peon REST API.

    Returns parsed JSON or None on failure.
    """
    url = f"{get_api_url()}{path}"
    body = json.dumps(payload).encode("utf-8") if payload is not None else None
    headers: dict[str, str] = {"Content-Type": "application/json"}
    api_key = get_api_key()
    if api_key:
        headers["X-API-Key"] = api_key
    req = urllib.request.Request(url, data=body, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return json.loads(resp.read())
    except (urllib.error.HTTPError, urllib.error.URLError, json.JSONDecodeError, OSError):
        return None


def extract_task_id_from_branch() -> int | None:
    """Extract task ID from the current git branch name.

    Expects branch names like 'task/123-some-title' or 'peon-xxx-N' worktree branches.
    """
    try:
        result = subprocess.run(
            ["git", "rev-parse", "--abbrev-ref", "HEAD"],
            capture_output=True, text=True, timeout=5,
        )
        if result.returncode != 0:
            return None
        branch = result.stdout.strip()

        import re

        # Match task/123-... pattern
        m = re.match(r"task/(\d+)", branch)
        if m:
            return int(m.group(1))

        # Match task-123-... pattern (common agent naming)
        m = re.match(r"task-(\d+)", branch)
        if m:
            return int(m.group(1))

        return None
    except (subprocess.TimeoutExpired, OSError):
        return None


