"""
A tiny web chat so you and Wayne can click and talk to the pilot in a browser.

    python app.py    ->  open http://localhost:5000

The answer streams in live (a typing effect). Includes the gentle cookie-based
per-session turn cap (no IP tracking). Requires ANTHROPIC_API_KEY.
"""

import os
import json
import uuid
import datetime
from flask import Flask, request, session, Response, stream_with_context
import rag

SESSION_MAX_TURNS = int(os.environ.get("SESSION_MAX_TURNS", "20"))
# Lightweight Q&A log so Wayne's "that felt off" comes with the actual question,
# answer, and cited sources. No IP or identity is recorded (matches the
# no-IP-tracking ethos). Set LOG_QA=0 to disable.
LOG_QA = os.environ.get("LOG_QA", "1") != "0"
LOG_DIR = os.environ.get(
    "LOG_DIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs"))
MAX_HISTORY_MSGS = int(os.environ.get("MAX_HISTORY_MSGS", "4"))  # conversation memory (2 exchanges)
CAP_MESSAGE = ("We've covered such good ground together — why not sit with what you've "
               "found before we go further? I'll be right here when you come back.")

# Per-session conversation memory + turn counts, held server-side, keyed by a
# conversation id (not stored in the cookie). Reset on restart.
_HISTORY = {}
_TURNS = {}

# Domains allowed to embed the guide in an iframe (the widget runs on these).
FRAME_ANCESTORS = os.environ.get(
    "FRAME_ANCESTORS",
    "'self' https://lifestream.org https://www.lifestream.org "
    "https://thegodjourney.com https://www.thegodjourney.com",
)
_SECURE_COOKIES = os.environ.get("COOKIE_SECURE", "1") != "0"

app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET", "dev-only-change-me")
# SameSite=None needs Secure; both are required for the fallback cookie to
# survive inside a cross-site iframe. (Locally over http, set COOKIE_SECURE=0.)
app.config.update(
    SESSION_COOKIE_SAMESITE="None" if _SECURE_COOKIES else "Lax",
    SESSION_COOKIE_SECURE=_SECURE_COOKIES,
)


@app.after_request
def _allow_embedding(resp):
    # Permit the two host sites (and only them) to frame the guide. CSP
    # frame-ancestors is used instead of X-Frame-Options so more than one
    # domain can embed it.
    resp.headers["Content-Security-Policy"] = f"frame-ancestors {FRAME_ANCESTORS};"
    resp.headers.pop("X-Frame-Options", None)
    return resp

# Load the store once at startup.
_chunks, _vectors = rag.load_store()

# Print a fingerprint of the loaded store so you can confirm this running server
# is using the latest ingest (not a stale in-memory copy from before a re-ingest).
try:
    import datetime as _dt
    _sp = os.path.join(os.path.dirname(os.path.abspath(__file__)), "store", "chunks.json")
    _mt = _dt.datetime.fromtimestamp(os.path.getmtime(_sp)).strftime("%Y-%m-%d %H:%M:%S")
    print(f"[Trail Guide] Loaded {len(_chunks):,} chunks | store built {_mt}", flush=True)
except Exception:
    pass

PAGE = """
<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>A Trail Guide to Wayne's Work</title>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>window.__SID__="%%SID%%";</script>
<style>
  body{font-family:Georgia,serif;max-width:640px;margin:40px auto;padding:0 16px;color:#222}
  h1{font-size:20px;color:#1F3864}
  #log{margin:20px 0}
  .msg{margin:14px 0;line-height:1.5}
  .msg p{margin:0 0 10px}
  .you{color:#555}.bot{color:#1F3864}
  .label{font-weight:bold}
  .src{font-size:12px;color:#888;margin-top:8px}
  .src ul{margin:4px 0 0;padding-left:18px}
  .src li{margin:2px 0}
  .src a{color:#2E75B6}
  .dots span{animation:blink 1.4s infinite both}
  .dots span:nth-child(2){animation-delay:.2s}
  .dots span:nth-child(3){animation-delay:.4s}
  @keyframes blink{0%,80%,100%{opacity:.2}40%{opacity:1}}
  form{display:flex;gap:8px}
  input[type=text]{flex:1;padding:10px;font-size:15px}
  input:disabled,button:disabled{opacity:.5}
  button{padding:10px 16px;font-size:15px;cursor:pointer}
</style>
%%EXTRA_HEAD%%
<h1>A Trail Guide to Wayne's Work</h1>
<p class="subtitle" style="color:#888;font-size:13px">An AI guide to Wayne's writing. Not Wayne himself.</p>
<div id="log"></div>
<form id="f"><input id="q" type="text" autocomplete="off"
  placeholder="Ask a question..."><button>Ask</button></form>
<script>
const log=document.getElementById('log'),f=document.getElementById('f'),q=document.getElementById('q'),btn=f.querySelector('button');
// Every link opens in a new tab so the Trail Guide conversation is never lost
// (a same-site link taking over the page would reload the widget and wipe it).
function retarget(root){root.querySelectorAll('a[href]').forEach(function(a){a.target='_blank';a.rel='noopener';});}
function esc(s){const d=document.createElement('div');d.textContent=s==null?'':s;return d.innerHTML;}
function add(cls,html){const d=document.createElement('div');d.className='msg '+cls;d.innerHTML=html;log.appendChild(d);window.scrollTo(0,document.body.scrollHeight);return d;}
function sourcesHtml(list){
  if(!list||!list.length)return '';
  const items=list.map(s=>{
    const inner=s.url?('<a href="'+esc(s.url)+'" target="_blank" rel="noopener">'+esc(s.label)+'</a>'):esc(s.label);
    return '<li>'+inner+'</li>';
  }).join('');
  return '<div class="src">Sources:<ul>'+items+'</ul></div>';
}
f.onsubmit=async e=>{
  e.preventDefault();
  const text=q.value.trim(); if(!text)return;
  q.value=''; q.disabled=true; btn.disabled=true;
  add('you','<b>You:</b> '+esc(text));
  const bot=add('bot','<span class="label">Trail Guide:</span> <span class="body"><span class="dots"><span>.</span><span>.</span><span>.</span></span></span>');
  const body=bot.querySelector('.body');
  let acc='', sources=[];
  try{
    const r=await fetch('/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({q:text,sid:window.__SID__||''})});
    const reader=r.body.getReader(), dec=new TextDecoder(); let buf='';
    while(true){
      const {value,done}=await reader.read();
      if(done)break;
      buf+=dec.decode(value,{stream:true});
      let nl;
      while((nl=buf.indexOf('\\n'))>=0){
        const line=buf.slice(0,nl).trim(); buf=buf.slice(nl+1);
        if(!line)continue;
        const msg=JSON.parse(line);
        if(msg.delta){acc+=msg.delta; body.innerHTML=marked.parse(acc); retarget(body); window.scrollTo(0,document.body.scrollHeight);}
        if(msg.done){sources=msg.sources||[];}
      }
    }
    body.innerHTML=marked.parse(acc)+sourcesHtml(sources);
    retarget(body);
  }catch(err){
    body.innerHTML='Sorry — something went wrong. Please try again.';
  }finally{
    q.disabled=false; btn.disabled=false; q.focus();
  }
};
</script>
"""


def _sources(hits, reply):
    """List only the sources the answer actually references (by name or link)."""
    rl = reply.lower()
    seen, out = set(), []
    for c, _ in hits:
        src = c["source"]
        if src in seen:
            continue
        seen.add(src)
        is_url = src.startswith("http")
        label = c.get("book_title") or rag.display_name(src)
        # Prefer a catalog link (e.g. a video's Lifestream page) over the raw
        # source URL (e.g. the Vimeo link).
        url = c.get("book_link") or (src if is_url else "")
        referenced = (url and url.lower() in rl) or (label and label.lower() in rl)
        if referenced:
            out.append({"label": label, "url": url})
    return out


def _line(obj):
    return json.dumps(obj) + "\n"


def _log_qa(question, answer, sources):
    """Append one Q&A to a monthly JSONL log. Never lets logging break a reply."""
    if not LOG_QA:
        return
    try:
        os.makedirs(LOG_DIR, exist_ok=True)
        rec = {
            "ts": datetime.datetime.now().isoformat(timespec="seconds"),
            "q": question,
            "a": answer,
            "sources": [s.get("label") for s in (sources or [])],
        }
        month = datetime.datetime.now().strftime("%Y%m")
        with open(os.path.join(LOG_DIR, f"qa-{month}.jsonl"), "a", encoding="utf-8") as f:
            f.write(json.dumps(rec, ensure_ascii=False) + "\n")
    except Exception:
        pass


_EMBED_CSS = (
    "<style>body{max-width:none;margin:0;padding:12px 16px 88px}"
    "h1,.subtitle{display:none}"
    "form{position:fixed;left:0;right:0;bottom:0;margin:0;background:#fff;"
    "padding:12px 16px;border-top:1px solid #eee}</style>"
)


def _render(sid, embed):
    return PAGE.replace("%%SID%%", sid).replace("%%EXTRA_HEAD%%", _EMBED_CSS if embed else "")


@app.route("/")
def home():
    session.setdefault("sid", uuid.uuid4().hex)
    sid = (request.args.get("sid") or "").strip() or session["sid"]
    return _render(sid, request.args.get("embed") == "1")


@app.route("/widget.js")
def widget_js():
    p = os.path.join(os.path.dirname(os.path.abspath(__file__)), "widget.js")
    with open(p, encoding="utf-8") as f:
        resp = Response(f.read(), mimetype="application/javascript")
    # Revalidate on each load so widget updates propagate without a stale cache.
    resp.headers["Cache-Control"] = "no-cache"
    return resp


@app.route("/widget-logo.png")
@app.route("/widget-logo-<variant>.png")
def widget_logo(variant=None):
    # Serve widget-logo.png (default) or a per-site variant like
    # widget-logo-lifestream.png. Variant is restricted to safe characters.
    name = "widget-logo.png" if not variant else f"widget-logo-{variant}.png"
    if variant and not variant.isalnum():
        return Response(status=404)
    p = os.path.join(os.path.dirname(os.path.abspath(__file__)), name)
    if not os.path.exists(p):
        return Response(status=404)
    with open(p, "rb") as f:
        return Response(f.read(), mimetype="image/png")


@app.route("/ask", methods=["POST"])
def ask():
    session.setdefault("sid", uuid.uuid4().hex)
    data = request.get_json(silent=True) or {}
    # A widget passes its own conversation token; the standalone page falls back
    # to the cookie session id.
    sid = (data.get("sid") or "").strip() or session["sid"]
    q = (data.get("q") or "").strip()
    turns = _TURNS.get(sid, 0)
    capped = turns >= SESSION_MAX_TURNS
    hist = _HISTORY.get(sid, [])

    # Decide/prepare everything that touches state BEFORE streaming starts.
    hits = None
    if not capped and q:
        _TURNS[sid] = turns + 1
        # Fold the previous question into retrieval so follow-ups ("that story")
        # still find the right passages.
        prev_user = next((m["content"] for m in reversed(hist) if m["role"] == "user"), "")
        rquery = f"{prev_user}\n{q}" if prev_user else q
        hits = rag.retrieve(rquery, _chunks, _vectors)

    def generate():
        if capped:
            yield _line({"delta": CAP_MESSAGE})
            yield _line({"done": True, "sources": []})
            return
        if not q:
            yield _line({"delta": "What would you like to explore?"})
            yield _line({"done": True, "sources": []})
            return
        parts = []
        for text in rag.answer_stream(q, hits, history=hist):
            parts.append(text)
            yield _line({"delta": text})
        reply = "".join(parts)
        _HISTORY[sid] = (hist + [{"role": "user", "content": q},
                                 {"role": "assistant", "content": reply}])[-MAX_HISTORY_MSGS:]
        srcs = _sources(hits, reply)
        _log_qa(q, reply, srcs)
        yield _line({"done": True, "sources": srcs})

    return Response(stream_with_context(generate()), mimetype="application/x-ndjson")


if __name__ == "__main__":
    app.run(debug=True, port=5000, threaded=True)
