"""Bridge token helpers — loopback auth for /v1/* routes."""

from __future__ import annotations

import os
import secrets
from pathlib import Path


def default_token_path() -> Path:
    return Path.home() / ".config" / "iuve-connect-agent" / "ui-bridge-token"


def resolve_or_create_token(*, token_path: Path | None = None) -> str:
    env_token = str(os.environ.get("IUVE_UI_BRIDGE_TOKEN") or "").strip()
    if env_token:
        return env_token

    path = token_path or default_token_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.is_file():
        existing = path.read_text(encoding="utf-8").strip()
        if existing:
            return existing

    token = secrets.token_urlsafe(32)
    path.write_text(token + "\n", encoding="utf-8")
    try:
        path.chmod(0o600)
    except OSError:
        pass
    return token


def extract_bearer_token(authorization: str | None, query_token: str | None = None) -> str:
    raw = str(authorization or "").strip()
    if raw.lower().startswith("bearer "):
        return raw[7:].strip()
    q = str(query_token or "").strip()
    return q
