import os
import logging
from typing import Optional

import httpx

logger = logging.getLogger(__name__)

RACE_API_BASE_URL = os.getenv("RACE_API_BASE_URL", "http://127.0.0.1:8080")
RACE_API_KEY = os.getenv("RACE_API_KEY")

# Every upload lands in this single, pre-provisioned collection — race-api has
# no self-service "create collection" endpoint for API-key consumers (only its
# admin API can get-or-create one), and no per-tenant isolation beyond it, so
# there is nothing to route on the caller's side. This ID has to be handed to
# us by race-api's admin and configured here, the same way RACE_API_KEY is.
RACE_RAG_COLLECTION_ID = os.getenv("RACE_RAG_COLLECTION_ID")

RACE_RAG_DOCUMENTS_URL = f"{RACE_API_BASE_URL}/v1/rag/documents"

# race-api's actual validation (live-tested against the running service — its
# own OpenAPI schema just types source_type as a bare string, this enum and
# the extension allowlist aren't documented anywhere):
#   source_type="text"        + a "text" form field  -> any plain text content
#   source_type="ocr_upload"  + a "file" upload       -> image/PDF only, run
#                                                        through race-api's OCR
# Anything else (.docx, .csv, ...) has no direct path — the caller must
# extract text itself first and send it through as source_type="text".
_OCR_UPLOAD_EXTENSIONS = {".pdf", ".png", ".jpg", ".jpeg", ".webp", ".tif", ".tiff", ".bmp"}
_TEXT_EXTENSIONS = {".txt"}

_http = httpx.AsyncClient(
    timeout=httpx.Timeout(connect=10.0, read=60.0, write=30.0, pool=5.0),
)


class RaceRagError(Exception):
    """A real error from race-api (bad file type, missing config, upstream
    failure) that the caller should surface to the user as an HTTP error —
    unlike e.g. _check_moderation's fail-open behavior elsewhere in this
    codebase, a broken upload must be visible to the person who tried it,
    not silently swallowed."""

    def __init__(self, status_code: int, detail: str):
        self.status_code = status_code
        self.detail = detail
        super().__init__(detail)


def _require_config() -> None:
    if not RACE_API_KEY:
        raise RaceRagError(500, "RACE_API_KEY is not configured")
    if not RACE_RAG_COLLECTION_ID:
        raise RaceRagError(500, "RACE_RAG_COLLECTION_ID is not configured")


async def upload_document(filename: str, content: bytes, content_type: Optional[str] = None) -> dict:
    """Uploads one document into the shared default race-api RAG collection.
    Raises RaceRagError on any failure (unsupported type, upstream error).
    """
    _require_config()

    ext = os.path.splitext(filename)[1].lower()
    headers = {"x-api-key": RACE_API_KEY}

    if ext in _OCR_UPLOAD_EXTENSIONS:
        data = {
            "collection_id": RACE_RAG_COLLECTION_ID,
            "source_type": "ocr_upload",
            "source_name": filename,
        }
        files = {"file": (filename, content, content_type or "application/octet-stream")}
        resp = await _http.post(RACE_RAG_DOCUMENTS_URL, data=data, files=files, headers=headers)
    elif ext in _TEXT_EXTENSIONS:
        try:
            text = content.decode("utf-8")
        except UnicodeDecodeError:
            raise RaceRagError(400, f"{filename}: not valid UTF-8 text")
        data = {
            "collection_id": RACE_RAG_COLLECTION_ID,
            "source_type": "text",
            "source_name": filename,
            "text": text,
        }
        resp = await _http.post(RACE_RAG_DOCUMENTS_URL, data=data, headers=headers)
    else:
        allowed = sorted(_OCR_UPLOAD_EXTENSIONS | _TEXT_EXTENSIONS)
        raise RaceRagError(415, f"Unsupported file type '{ext}'. Allowed: {allowed}")

    if resp.status_code >= 400:
        logger.warning(f"race-api RAG upload failed | status={resp.status_code} | body={resp.text[:300]}")
        raise RaceRagError(resp.status_code, resp.text)
    return resp.json()


async def list_documents(limit: int = 20, offset: int = 0) -> list:
    """Lists every document in the shared default collection (tenant-wide —
    race-api itself has no per-user or per-company scoping)."""
    _require_config()
    headers = {"x-api-key": RACE_API_KEY}
    resp = await _http.get(
        RACE_RAG_DOCUMENTS_URL, params={"limit": limit, "offset": offset}, headers=headers
    )
    if resp.status_code >= 400:
        logger.warning(f"race-api RAG list failed | status={resp.status_code} | body={resp.text[:300]}")
        raise RaceRagError(resp.status_code, resp.text)
    return resp.json()
