"""Shared HTTP client and output helpers for CLI commands."""

from __future__ import annotations

import json

import httpx
from proxym.config import get_settings


def make_client(base: str = None, key: str = None) -> httpx.Client:
    """Create HTTP client with configuration from settings."""
    settings = get_settings()
    base_url = base or settings.default_proxy_url
    api_key = key or settings.default_api_key

    return httpx.Client(
        base_url=base_url,
        headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
        timeout=10,
    )


def print_json(data):
    print(json.dumps(data, indent=2, ensure_ascii=False))


def print_table(rows: list[dict], columns: list[str], widths: list[int] | None = None):
    if not rows:
        print("  (empty)")
        return
    if not widths:
        widths = [max(len(c), max(len(str(r.get(c, ""))[:40]) for r in rows)) for c in columns]
    header = "  ".join(c.ljust(w) for c, w in zip(columns, widths))
    print(f"\033[1m{header}\033[0m")
    print("  ".join("─" * w for w in widths))
    for r in rows:
        line = "  ".join(str(r.get(c, ""))[:w].ljust(w) for c, w in zip(columns, widths))
        print(line)
