"""Read the Trail Guide Q&A log in plain, human-readable form.

Run it from the app folder on the server (no venv needed):

    python3 viewlog.py                          # the 20 most recent exchanges
    python3 viewlog.py 50                       # the 50 most recent
    python3 viewlog.py grace                    # only exchanges mentioning "grace"

  Date filtering (dates are YYYY-MM-DD):
    python3 viewlog.py --today                  # just today
    python3 viewlog.py --since 2026-08-01       # on/after Aug 1
    python3 viewlog.py --until 2026-08-07       # on/before Aug 7
    python3 viewlog.py --since 2026-08-01 --until 2026-08-07   # a range
    python3 viewlog.py --since 2026-08-01 grace # a range, only ones mentioning "grace"

Newest appears at the bottom. When you give a date range or a word, ALL matching
exchanges are shown; otherwise the most recent 20 (or N).
"""
import json
import glob
import os
import sys
import datetime
import argparse

BASE = os.path.dirname(os.path.abspath(__file__))

ap = argparse.ArgumentParser(add_help=True)
ap.add_argument("query", nargs="?", help="a number (last N) or a word to filter by")
ap.add_argument("--since", metavar="YYYY-MM-DD", help="only entries on/after this date")
ap.add_argument("--until", metavar="YYYY-MM-DD", help="only entries on/before this date")
ap.add_argument("--today", action="store_true", help="only today's entries")
args = ap.parse_args()

rows = []
for fp in sorted(glob.glob(os.path.join(BASE, "logs", "qa-*.jsonl"))):
    with open(fp, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                rows.append(json.loads(line))
            except Exception:
                pass

if not rows:
    print("No questions logged yet.")
    sys.exit(0)

total = len(rows)

# --- date range ---
since, until = args.since, args.until
if args.today:
    since = until = datetime.date.today().isoformat()
dated = bool(since or until)
if dated:
    rows = [r for r in rows
            if (not since or r.get("ts", "")[:10] >= since)
            and (not until or r.get("ts", "")[:10] <= until)]

# --- number (last N) or keyword ---
limit, term = None, None
if args.query:
    if args.query.isdigit():
        limit = int(args.query)
    else:
        term = args.query
if term:
    rows = [r for r in rows if term.lower() in (r.get("q", "") + " " + r.get("a", "")).lower()]

# --- selection ---
if dated or term:
    selected = rows                      # a deliberate scope -> show all matches
elif limit:
    selected = rows[-limit:]
else:
    selected = rows[-20:]

scope = []
if since or until:
    scope.append(f"{since or '…'} to {until or '…'}")
if term:
    scope.append(f'mentioning "{term}"')
scope = (" — " + ", ".join(scope)) if scope else ""
print(f"{total} exchanges logged; showing {len(selected)}{scope}.\n")

for r in selected:
    print(f"[{r.get('ts', '')}]")
    print(f"Q: {r.get('q', '')}")
    print(f"A: {r.get('a', '')}")
    src = [s for s in (r.get("sources") or []) if s]
    if src:
        print("Sources: " + ", ".join(src))
    print("-" * 70)
