#!/usr/bin/env python3
"""ask.py — your Modern AI Pro practice TA, from the terminal. It knows YOUR
class, schedule, setup progress, and placement (that's your personal key at work).

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

  python ask.py                          # interactive — remembers the conversation
  python ask.py "when does my class start?"    # one-shot
  python ask.py "why this error?" < err.txt    # attach a pasted error

Key: put your personal key in a .env next to this file (MAI_API_KEY=mai_...) —
it's in your welcome email. Get this file:
  curl -O https://study.modernaipro.com/practice/ask.py

Unlike the AI Architect course's ask.py, all personalization happens SERVER-side
from your key — this client stays tiny. Standard library only.
"""
from __future__ import annotations

import json
import os
import pathlib
import platform
import re
import sys
import urllib.error
import urllib.request

# ── .env (KEY=VALUE) from cwd / script dir — same shim the labs use ─────────────
_here = pathlib.Path(__file__).resolve().parent if "__file__" in globals() else pathlib.Path.cwd()
for _cand in (pathlib.Path(".env"), _here / ".env"):
    if _cand.exists():
        try:
            _txt = _cand.read_text(encoding="utf-8-sig")
        except (OSError, UnicodeDecodeError):
            _txt = ""
        for _ln in _txt.splitlines():
            _ln = _ln.strip()
            if _ln.startswith("export "):
                _ln = _ln[7:].lstrip()
            if _ln and not _ln.startswith("#") and "=" in _ln:
                _k, _v = _ln.split("=", 1)
                os.environ.setdefault(_k.strip(), _v.strip().strip("'\""))
        break

BASE = os.environ.get("MAI_BASE_URL", "https://study.modernaipro.com/api/llm/v1").rstrip("/")
KEY = os.environ.get("MAI_API_KEY", "").strip() or os.environ.get("OPENAI_API_KEY", "").strip()
UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
      "(KHTML, like Gecko) mai-practice-ask/1.0")

_TTY = sys.stdout.isatty()
def _c(code: str) -> str:
    return code if _TTY else ""
BOLD, DIM, RESET = _c("\033[1m"), _c("\033[2m"), _c("\033[0m")
CYAN, YEL, GRN, RED = _c("\033[36m"), _c("\033[33m"), _c("\033[32m"), _c("\033[31m")

# Light machine snapshot — enough for setup help, nothing heavier. (Your account
# context — class, checklist, placement — is attached by the SERVER from your key.)
def snapshot() -> str:
    keys = ", ".join(f"{k}={'set' if os.environ.get(k) else 'unset'}"
                     for k in ("MAI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY"))
    return (f"os: {platform.system()} {platform.release()} {platform.machine()} · "
            f"python {platform.python_version()} · {keys} · "
            f".env: {'yes' if (pathlib.Path('.env').exists() or (_here / '.env').exists()) else 'no'}")

def render(text: str) -> None:
    out, in_code = [], False
    for line in text.split("\n"):
        if line.strip().startswith("```"):
            in_code = not in_code
            out.append((DIM + "  ┄┄┄┄┄┄┄┄┄┄" + RESET) if _TTY else line)
            continue
        if in_code:
            out.append(CYAN + "  " + line + RESET)
            continue
        s = line
        if re.match(r"^#{1,6}\s", s):
            s = BOLD + re.sub(r"^#{1,6}\s", "", s) + RESET
        s = re.sub(r"\*\*(.+?)\*\*", BOLD + r"\1" + RESET, s)
        s = re.sub(r"`([^`]+)`", CYAN + r"\1" + RESET, s)
        s = re.sub(r"^(\s*)[-*]\s", r"\1• ", s)
        out.append(s)
    print("\n".join(out))

def call(question: str, history: list) -> str | None:
    req = urllib.request.Request(
        BASE + "/ask", method="POST",
        headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json", "User-Agent": UA},
        data=json.dumps({"question": question, "history": history[-8:]}).encode("utf-8"))
    try:
        with urllib.request.urlopen(req, timeout=90) as r:
            d = json.loads(r.read().decode("utf-8"))
            return (d.get("choices") or [{}])[0].get("message", {}).get("content") or "(no answer returned)"
    except urllib.error.HTTPError as e:
        try:
            msg = json.loads(e.read().decode("utf-8", "ignore"))["error"]["message"]
        except Exception:
            msg = f"HTTP {e.code}"
        print(RED + msg + RESET)   # the server's message says what to do (rotation / cap / rate)
    except urllib.error.URLError as e:
        print(RED + f"Couldn't reach the TA ({e.reason}). Check your connection." + RESET)
    return None

# Persisted thread — quit and re-launch continues the same conversation.
_HISTORY = _here / ".ask_history.json"

def _load_history() -> list:
    try:
        data = json.loads(_HISTORY.read_text())
        return [{"role": m["role"], "content": m["content"]} for m in data
                if isinstance(m, dict) and m.get("role") in ("user", "assistant") and m.get("content")][-8:]
    except Exception:
        return []

def _save_history(convo: list) -> None:
    try:
        _HISTORY.write_text(json.dumps(convo[-8:]))
    except Exception:
        pass

def main() -> None:
    if not KEY:
        print(YEL + "No key found. Put your personal key in a .env next to this file:\n"
              "  MAI_API_KEY=mai_...   (it's in your welcome email)" + RESET)
        return
    args = " ".join(sys.argv[1:]).strip()
    piped = "" if sys.stdin.isatty() else sys.stdin.read().strip()

    if args or piped:  # one-shot
        q = args or "What's going wrong here and how do I fix it?"
        if piped:
            q += "\n\nPasted error / output:\n" + piped[:6000]
        q += "\n\n(my machine: " + snapshot() + ")"
        ans = call(q, [])
        if ans:
            print()
            render(ans)
            print()
        return

    convo = _load_history()
    resumed = f" · resumed {len(convo) // 2} earlier turn(s), 'reset' to start fresh" if convo else ""
    print(f"{BOLD}Modern AI Pro · practice TA{RESET} {DIM}· knows your class + setup · remembers this chat{resumed} · q to quit{RESET}")
    while True:
        try:
            q = input(f"{GRN}TA ›{RESET} ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            break
        if q.lower() in ("q", "quit", "exit"):
            break
        if q.lower() in ("reset", "forget", "clear"):
            convo = []
            try:
                _HISTORY.unlink()
            except OSError:
                pass
            print(DIM + "↳ memory cleared — fresh thread." + RESET)
            continue
        if not q:
            continue
        ans = call(q + "\n\n(my machine: " + snapshot() + ")", convo)
        if ans is None:
            continue
        convo += [{"role": "user", "content": q}, {"role": "assistant", "content": ans}]
        _save_history(convo)
        print()
        render(ans)
        print()
    print(DIM + "bye 👋" + RESET)

if __name__ == "__main__":
    main()
