"""modernai — the Modern AI Pro practice kit, in one file. Works in any notebook.

MIRROR: canonical source is github.com/balajivis/mai-operator-labs (class-resources/mai-operator-labs) — edit there, copy here.

Get it (one cell):
    import urllib.request
    urllib.request.urlretrieve("https://study.modernaipro.com/practice/modernai.py", "modernai.py")

Use it:
    import modernai
    print(modernai.ask("What's left in my setup before Friday?"))   # your personal TA
    print(modernai.complete("Explain embeddings in two sentences")) # plain model call
    vecs = modernai.embed(["parental leave", "time off for a baby"])  # meaning-vectors
    modernai.usage()                                                # your monthly meter

Your key: set MAI_API_KEY (in a .env, your shell, or Colab's secrets panel as
MAI_API_KEY). It's the personal `mai_...` key from your welcome email — one per
level, with that level's practice budget, valid through your two-week course
window. If no key is found you'll be prompted once (hidden, never stored).

Under the hood this is nothing exotic — the standard OpenAI-compatible API. The
3-line equivalent with the official SDK, which works against ANY provider:

    from openai import OpenAI
    client = OpenAI(api_key="mai_...", base_url="https://study.modernaipro.com/api/llm/v1")
    client.chat.completions.create(model="small", messages=[{"role": "user", "content": "hi"}])

Graduating to your own provider key later is changing two strings. That's the point.
"""
from __future__ import annotations

import json
import os
import pathlib
import urllib.error
import urllib.request

# Cloudflare (in front of modernaipro.com) 403s the default python-urllib UA.
_UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
       "(KHTML, like Gecko) modernai-practice/1.0")

_key_cache: str | None = None


def _load_dotenv() -> None:
    """Pick up MAI_API_KEY / MAI_BASE_URL from a .env in the cwd or its parent (no dependency)."""
    for cand in (pathlib.Path(".env"), pathlib.Path("..") / ".env"):
        if not cand.exists():
            continue
        try:
            for line in cand.read_text(encoding="utf-8-sig").splitlines():
                line = line.strip()
                if line.startswith("export "):
                    line = line[7:].lstrip()
                if line and not line.startswith("#") and "=" in line:
                    k, v = line.split("=", 1)
                    v = v.strip().strip("'\"")
                    os.environ.setdefault(k.strip(), v)
        except OSError:
            pass
        break


# .env must load BEFORE the base URL resolves, or a MAI_BASE_URL override there
# is silently ignored (the bug: BASE_URL used to be computed at import, pre-.env).
_load_dotenv()
BASE_URL = os.environ.get("MAI_BASE_URL", "https://study.modernaipro.com/api/llm/v1").rstrip("/")


def _get_key() -> str:
    """MAI_API_KEY / OPENAI_API_KEY from env → .env → Colab secrets → one hidden prompt."""
    global _key_cache
    if _key_cache:
        return _key_cache
    _load_dotenv()
    key = os.environ.get("MAI_API_KEY", "").strip() or os.environ.get("OPENAI_API_KEY", "").strip()
    if not key:
        try:  # Colab secrets panel (the 🔑 icon): add MAI_API_KEY there once
            from google.colab import userdata  # type: ignore
            key = (userdata.get("MAI_API_KEY") or "").strip()
        except Exception:
            pass
    if not key:
        import getpass
        key = getpass.getpass("Paste your MAI key (mai_..., from your welcome email): ").strip()
    if not key:
        raise RuntimeError("No key. Set MAI_API_KEY in your .env or Colab secrets and retry.")
    _key_cache = key
    return key


class ModernAIError(RuntimeError):
    """A server-explained failure — the message is the server's own words
    (rotation, monthly cap, rate limit), so read it: it says what to do."""


def _request(method: str, path: str, payload: dict | None = None) -> dict:
    req = urllib.request.Request(
        BASE_URL + path, method=method,
        headers={"Authorization": f"Bearer {_get_key()}",
                 "Content-Type": "application/json", "User-Agent": _UA},
        data=json.dumps(payload).encode("utf-8") if payload is not None else None)
    try:
        with urllib.request.urlopen(req, timeout=90) as r:
            return json.loads(r.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        try:
            detail = json.loads(e.read().decode("utf-8", "ignore"))["error"]["message"]
        except Exception:
            detail = f"HTTP {e.code}"
        raise ModernAIError(detail) from None
    except urllib.error.URLError as e:
        raise ModernAIError(f"Couldn't reach Modern AI Pro ({e.reason}). Check your connection.") from None


def complete(prompt_or_messages, max_tokens: int = 800) -> str:
    """A plain model call (the same endpoint every lab uses).

    complete("one sentence on RAG")  or  complete([{"role":"user","content":"..."}])
    """
    if isinstance(prompt_or_messages, str):
        messages = [{"role": "user", "content": prompt_or_messages}]
    else:
        messages = list(prompt_or_messages)
    d = _request("POST", "/chat/completions", {"messages": messages, "max_tokens": max_tokens})
    return (d.get("choices") or [{}])[0].get("message", {}).get("content") or ""


_thread: list[dict] = []  # ask()'s in-notebook memory (last few turns)


def ask(question: str, fresh: bool = False) -> str:
    """Ask YOUR practice TA — it knows your enrollment, class schedule, setup
    checklist, and placement (that's what the personal key is for). Remembers
    the conversation within this notebook session; ask(..., fresh=True) resets.
    """
    global _thread
    if fresh:
        _thread = []
    d = _request("POST", "/ask", {"question": question, "history": _thread[-8:]})
    answer = (d.get("choices") or [{}])[0].get("message", {}).get("content") or "(no answer)"
    _thread += [{"role": "user", "content": question}, {"role": "assistant", "content": answer}]
    return answer


def embed(texts) -> list:
    """Turn text into meaning-vectors (semantic search, RAG). Accepts one string
    or a list (max 64 per call); returns one vector per input, in order."""
    if isinstance(texts, str):
        texts = [texts]
    d = _request("POST", "/embeddings", {"input": texts})
    return [row["embedding"] for row in d["data"]]


def usage(quiet: bool = False) -> dict:
    """This key's meter against its level budget. Returns the dict; prints a summary."""
    d = _request("GET", "/usage")
    # Accept both server shapes: per-key ({calls, tokens}) and the earlier
    # monthly one ({month_calls, month_tokens}) — the client must never crash
    # just because the server is a deploy behind.
    calls = d.get("calls", d.get("month_calls", 0))
    tokens = d.get("tokens", d.get("month_tokens", 0))
    if not quiet:
        print(f"Used:   {calls:,} calls · {tokens:,} tokens")
        print(f"Budget: {d['cap_calls']:,} calls · {d['cap_tokens']:,} tokens (this level's key)")
        if d.get("over_cap"):
            print("⚠ This key's budget is used up — your next level comes with a fresh key.")
    return d
