import re
import asyncio
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_RAG_QUERY_URL = f"{RACE_API_BASE_URL}/v1/rag/query"

# 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()


async def query_collection(query: str, k: int = 5) -> list:
    """Retrieves the top-k chunks most relevant to `query` from the shared
    default RAG collection via race-api's POST /v1/rag/query (request shape
    confirmed against race-api's live OpenAPI schema: {query, collection_id,
    k, document_id} with only `query` required).

    Unlike upload_document/list_documents, this fails open — returns []
    on missing config, network error, or an unexpected response shape —
    rather than raising, the same "a broken retrieval shouldn't break the
    whole HR answer" contract ai_service._call_race_brave_search already
    uses for web search. The 200 response schema isn't documented anywhere
    (race-api's own OpenAPI spec leaves it as an untyped `{}`), so the
    shape below is a best-effort guess — verify against a live call once
    RACE_API_KEY/RACE_RAG_COLLECTION_ID are valid and adjust _chunk_text's
    key list if the real field names differ.
    """
    if not RACE_API_KEY or not RACE_RAG_COLLECTION_ID:
        return []
    headers = {"x-api-key": RACE_API_KEY, "Content-Type": "application/json"}
    payload = {"query": query, "collection_id": RACE_RAG_COLLECTION_ID, "k": k}
    try:
        resp = await _http.post(RACE_RAG_QUERY_URL, json=payload, headers=headers)
        resp.raise_for_status()
        data = resp.json()
    except Exception as e:
        logger.warning(f"race-api RAG query failed (continuing without it): {e}")
        return []

    if isinstance(data, list):
        return _drop_personal_records(data)
    if isinstance(data, dict):
        for key in ("results", "chunks", "matches", "data"):
            value = data.get(key)
            if isinstance(value, list):
                return _drop_personal_records(value)
    return []


def _tidy_source_name(raw: str) -> str:
    """"remote-work-policy_1790078260_94dXId.pdf" -> "Remote Work Policy"."""
    name = (raw or "").rsplit(".", 1)[0]
    name = re.sub(r"_\d{6,}_[A-Za-z0-9]+$", "", name)
    return re.sub(r"[-_]+", " ", name).strip().title() or "Policy document"


# Words in a policy's name that don't identify it ("Leave Policy" is found by
# "leave", not by "policy").
_TITLE_FILLER = frozenset({"policy", "policies", "and", "the", "of", "for", "&"})
_POLICY_MENTION_RE = re.compile(r"\bpolic(?:y|ies)\b", re.IGNORECASE)
_WORD_RE = re.compile(r"[a-z]+")


def documents_named_in(query: str, documents: list) -> list:
    """The documents whose policy the query NAMES: "show my leave policy" ->
    Leave Policy, "what does the payroll policy say" -> Payroll And Benefits
    Policy. Needs the word "policy" and a distinctive word of the policy's own
    name (3+ letters, so "it" in "IT And Security" never matches everything).

    Empty when no policy is named — the caller then searches every document,
    because a question like "what is the notice period" can be answered by
    several of them."""
    text = (query or "").lower()
    if not _POLICY_MENTION_RE.search(text):
        return []
    words = set(_WORD_RE.findall(text))
    named = []
    for doc in documents:
        title_words = {w for w in _WORD_RE.findall(_tidy_source_name(doc.get("source_name") or "").lower())
                       if w not in _TITLE_FILLER and len(w) >= 3}
        if title_words & words:
            named.append(doc)
    return named


# One person's record - a payslip, an ID number - is never policy. A real
# payslip uploaded to the shared collection was quoted back to "Who has the
# highest salary in the company?" (HAI-SEC-02 re-run, 29 Oct). Whatever is
# uploaded, such a chunk never reaches the model.
_PERSONAL_RECORD_RES = (
    re.compile(r"\bpay\s*slip\b\s*:|\bsalary\s+slip\b|\bnet\s+(?:salary\s+)?payable\b", re.IGNORECASE),
    re.compile(r"\b[A-Z]{5}\d{4}[A-Z]\b"),                       # PAN
    re.compile(r"\b(?:aadh?aa?r|uid)\b[^\n]{0,40}?\b\d{4}\s?\d{4}\s?\d{4}\b", re.IGNORECASE),
    re.compile(r"\b(?:bank\s+)?a/?c\s*(?:no|number)\b[^\n]{0,20}\d{9,}", re.IGNORECASE),
)


def _is_personal_record(text: str) -> bool:
    return any(r.search(text or "") for r in _PERSONAL_RECORD_RES)


def _drop_personal_records(chunks: list) -> list:
    kept = [c for c in chunks if not _is_personal_record(_chunk_text(c))]
    if len(kept) != len(chunks):
        logger.warning("[RAG] dropped %d chunk(s) holding a personal record (payslip / ID number) - "
                       "remove that document from the policy collection", len(chunks) - len(kept))
    return kept


def _dedupe_chunks(chunks: list) -> list:
    """Drops a chunk whose text was already seen. Several policies are uploaded
    twice, so every excerpt from them arrived twice — doubling the prompt the
    summarizer has to read for no new information."""
    seen, out = set(), []
    for c in chunks:
        key = " ".join(_chunk_text(c).split()).lower()
        if key and key in seen:
            continue
        seen.add(key)
        out.append(c)
    return out


async def query_all_documents(query: str, k_per_doc: int = 3) -> list:
    """Retrieve from EVERY document in the collection, not just the global top-k.

    A plain top-k over the whole collection is dominated by whichever document
    has the most lexically similar text, which on this collection means the two
    big ones. Measured: "work from home policy" came back with the earned-leave
    carry-forward chunk as its top hit while remote-work-policy.pdf -- 536
    characters, the entire answer -- was never reached. Six of the seven
    documents were effectively invisible.

    So each document is queried separately with race-api's document_id filter
    and given its own budget. A short policy competes on its own terms rather
    than against a 15k-character one, and a question whose answer is spread
    across several documents (probation appears in leave, performance AND
    separation policy) gets all of them.

    Chunks come back tagged with the document they came from, so the answer can
    say which policy a rule is from. Fails open like query_collection: a
    document that errors is skipped, not fatal.
    """
    if not RACE_API_KEY or not RACE_RAG_COLLECTION_ID:
        return []
    try:
        documents = await list_documents(limit=100)
    except Exception as e:
        logger.warning(f"race-api RAG document list failed, falling back to flat query: {e}")
        return await query_collection(query, k=k_per_doc * 3)
    if not documents:
        return []

    # A question that NAMES a policy is answered from that policy. Measured on
    # "show my leave policy": every document's excerpts together were ~89k
    # characters (~18.6k prompt tokens) and the summarizer spent ~10s reading
    # them, most of it other policies, duplicates and placeholder files.
    named = documents_named_in(query, documents)
    if named:
        logger.info("[RAG] %r names %s — searching only those",
                    query[:60], sorted({_tidy_source_name(d.get("source_name") or "") for d in named}))
        documents = named

    headers = {"x-api-key": RACE_API_KEY, "Content-Type": "application/json"}

    async def _one(doc: dict) -> list:
        doc_id = doc.get("document_id")
        if not doc_id:
            return []
        payload = {"query": query, "collection_id": RACE_RAG_COLLECTION_ID,
                   "k": k_per_doc, "document_id": doc_id}
        try:
            resp = await _http.post(RACE_RAG_QUERY_URL, json=payload, headers=headers)
            resp.raise_for_status()
            data = resp.json()
        except Exception as e:
            logger.warning(f"race-api RAG query failed for {doc.get('source_name')}: {e}")
            return []
        chunks = data if isinstance(data, list) else next(
            (data[key] for key in ("results", "chunks", "matches", "data")
             if isinstance(data, dict) and isinstance(data.get(key), list)), [])
        source = _tidy_source_name(doc.get("source_name") or "")
        for c in chunks:
            if isinstance(c, dict):
                c["_source"] = source
        return chunks

    gathered = await asyncio.gather(*[_one(d) for d in documents], return_exceptions=True)
    out: list = []
    for result in gathered:
        if isinstance(result, list):
            out.extend(result)
    out = _drop_personal_records(_dedupe_chunks(out))
    logger.info("[RAG] %r -> %d chunks across %d documents",
                query[:60], len(out), len(documents))
    return out


def _chunk_text(chunk) -> str:
    if not isinstance(chunk, dict):
        return str(chunk) if chunk else ""
    for key in ("content", "text", "chunk_text", "chunk", "passage"):
        value = chunk.get(key)
        if isinstance(value, str) and value.strip():
            return value.strip()
    return ""


def format_retrieved_chunks(chunks: list) -> str:
    """Joins retrieved chunk texts into one plain-text block, dropping any
    chunk whose text couldn't be found under a guessed key (see
    query_collection's docstring on the unverified response shape).

    Chunks carrying a "_source" (everything from query_all_documents) are
    grouped under their document's name. Without that, excerpts from seven
    different policies arrive as one undifferentiated wall and the answer
    cannot say which policy a rule came from -- or notice that it is reading
    a leave rule while being asked about remote work.
    """
    grouped: dict = {}
    loose: list = []
    for c in chunks:
        text = _chunk_text(c)
        if not text or _is_personal_record(text):
            continue
        source = c.get("_source") if isinstance(c, dict) else None
        if source:
            grouped.setdefault(source, []).append(text)
        else:
            loose.append(text)

    blocks = [f"### From: {source}\n\n" + "\n\n".join(texts)
              for source, texts in grouped.items()]
    blocks.extend(loose)
    return "\n\n---\n\n".join(blocks)
