"""HTTP client wrapper for FastAPI backend."""

import os

import httpx
import streamlit as st

API_URL = os.environ.get("API_URL", "http://localhost:8000")


def get_headers() -> dict:
    token = st.session_state.get("access_token")
    if token:
        return {"Authorization": f"Bearer {token}"}
    return {}


def post(path: str, **kwargs) -> httpx.Response:
    return httpx.post(f"{API_URL}{path}", headers=get_headers(), timeout=30, **kwargs)


def get(path: str, **kwargs) -> httpx.Response:
    return httpx.get(f"{API_URL}{path}", headers=get_headers(), timeout=30, **kwargs)


def delete(path: str, **kwargs) -> httpx.Response:
    return httpx.delete(f"{API_URL}{path}", headers=get_headers(), timeout=30, **kwargs)


def upload_file(path: str, file) -> httpx.Response:
    return httpx.post(
        f"{API_URL}{path}",
        headers=get_headers(),
        files={"file": (file.name, file, "text/csv")},
        timeout=60,
    )


def register(email: str, password: str, name: str | None = None) -> dict | None:
    data = {"email": email, "password": password}
    if name:
        data["name"] = name
    resp = httpx.post(f"{API_URL}/auth/register", json=data, timeout=10)
    if resp.status_code == 201:
        return resp.json()
    return None


def login(email: str, password: str) -> dict | None:
    resp = httpx.post(
        f"{API_URL}/auth/login", json={"email": email, "password": password}, timeout=10
    )
    if resp.status_code == 200:
        return resp.json()
    return None


def is_authenticated() -> bool:
    return bool(st.session_state.get("access_token"))
