#!/usr/bin/env python3
"""Lie detector examiner (written by Claude; runs on the Mac).

Shows each question on a local page, records the fork's numbers and how long the
answer takes, saves a camera photo per answer, asks a separate Claude for its
guesses, SAVES them, and only then lets them be revealed with the two lights.

The true answers are never typed in. The numbers are never changed.
This measures what happens at the fingers. It cannot really detect lies.

  python3 examiner.py practice   (calm questions only, no Claude)
  python3 examiner.py            (the real test, one take)
"""
import json, os, re, shutil, statistics, subprocess, sys, tempfile, threading, time, webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

import breath_test as bt

HERE = os.path.dirname(os.path.abspath(__file__))
CAMERA = "MacBook Air Camera"
PORT = 0  # 0 = any free port (8765 is used by something else on this Mac)
BASELINE_SECONDS = 45
AFTER_ANSWER_SECONDS = 12
TOUCH_LEVEL = 20

CALM = [
    "Are you sitting down right now?",
    "Are your fingers on the sensor?",
    "Is there a screen in front of you?",
]
REAL = [
    "Have you ever ridden a horse?",
    "Have you ever seen a shooting star?",
    "Have you ever been on a boat?",
    "Can you whistle?",
    "Do you know how to juggle?",
    "Have you ever fallen asleep during a movie?",
    "Can you snap your fingers?",
    "Have you ever sung in the shower?",
    "Can you touch your nose with your tongue?",
    "Have you ever pretended to like a gift?",
]

state = {"phase": "start", "big": "Press SPACE to start", "small": "", "values": [], "touch": False}
samples = []          # (time, value)
keys = []             # keys pressed on the page
lock = threading.Lock()
serial_error = []

PAGE = """<!doctype html><meta charset="utf-8"><title>Lie detector</title>
<style>body{margin:0;background:#0d1117;color:#eee;font-family:-apple-system,sans-serif;text-align:center}
#big{font-size:5vw;font-weight:700;margin:8vh 4vw 2vh;min-height:13vw}#small{font-size:2vw;color:#9aa;min-height:3vw}
canvas{width:94vw;height:36vh;background:#161b22;border-radius:12px}#warn{color:#ff6b6b;font-size:2vw;min-height:3vw}</style>
<div id="big"></div><div id="small"></div><div id="warn"></div><canvas id="c" width="1600" height="500"></canvas>
<script>
const c=document.getElementById('c'),g=c.getContext('2d');
async function tick(){try{const s=await(await fetch('/state')).json();
big.textContent=s.big;small.textContent=s.small;
warn.textContent=(!s.touch&&['baseline','question','after'].includes(s.phase))?'No contact with the fork':'';
g.clearRect(0,0,1600,500);const v=s.values;if(v.length){const top=Math.max(400,...v);
g.strokeStyle='#3fb950';g.lineWidth=4;g.beginPath();v.forEach((y,i)=>{const px=i*1600/599,py=480-y*460/top;i?g.lineTo(px,py):g.moveTo(px,py)});g.stroke();
g.fillStyle='#eee';g.font='36px sans-serif';g.textAlign='left';g.fillText(v[v.length-1],20,45)}}catch(e){}
setTimeout(tick,200)}
document.addEventListener('keydown',e=>{const k=e.key===' '?'space':e.key.toLowerCase();
if(['space','y','n'].includes(k)){e.preventDefault();if(!e.repeat)fetch('/key',{method:'POST',body:k})}});
tick();
</script>"""


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def reply(self, body, kind):
        self.send_response(200)
        self.send_header("Content-Type", kind + "; charset=utf-8")
        self.end_headers()
        self.wfile.write(body.encode())

    def do_GET(self):
        if self.path == "/state":
            with lock:
                data = dict(state, values=[v for _, v in samples[-600:]])
            data["touch"] = bool(data["values"]) and data["values"][-1] > TOUCH_LEVEL
            self.reply(json.dumps(data), "application/json")
        else:
            self.reply(PAGE, "text/html")

    def do_POST(self):
        body = self.rfile.read(int(self.headers.get("Content-Length", 0))).decode()
        keys.append((time.time(), body))
        self.reply("ok", "text/plain")


def show(phase, big, small=""):
    state.update(phase=phase, big=big, small=small)


def wait_key(allowed):
    keys.clear()
    while True:
        check_serial()
        for t, k in list(keys):
            if k in allowed:
                return t, k
        time.sleep(0.02)


def check_serial():
    if serial_error:
        show("error", "Lost the Arduino", "Check the USB cable, then start again.")
        time.sleep(2)
        sys.exit(serial_error[0])


def pause(seconds):
    end = time.time() + seconds
    while time.time() < end:
        check_serial()
        time.sleep(0.1)


def read_serial(fd):
    try:
        for value in bt.readings(fd):
            with lock:
                samples.append((time.time(), value))
    except BaseException as e:  # includes the "no numbers" exit
        serial_error.append(str(e))


def window(a, b):
    with lock:
        return [(t, v) for t, v in samples if a <= t <= b]


def photo(path):
    subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-f", "avfoundation", "-framerate", "30",
                    "-video_size", "1280x720", "-i", CAMERA, "-ss", "1", "-frames:v", "1", path],
                   stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20, check=False)


def ask(number, kind, text, folder):
    show("question", text, "Y = yes     N = no")
    asked = time.time()
    subprocess.run(["say", text], check=False)
    spoken = time.time()
    answered, key = wait_key({"y", "n"})
    shot = os.path.join(folder, f"{kind}-{number}.jpg")
    camera = threading.Thread(target=photo, args=(shot,))
    camera.start()
    show("after", "Stay still", "Breathe normally")
    pause(AFTER_ANSWER_SECONDS)
    camera.join()

    before = [v for _, v in window(asked - 3, asked)] or [0]
    during = window(asked, answered + AFTER_ANSWER_SECONDS)
    values = [v for _, v in during]
    touching = [v for v in values if v > TOUCH_LEVEL]
    base = statistics.median(before)
    per_second = {}
    for t, v in during:
        per_second.setdefault(int(t - asked), []).append(v)
    return {
        "number": number, "kind": kind, "question": text, "answer_given": "yes" if key == "y" else "no",
        "seconds_to_answer": round(max(0.0, answered - spoken), 2),
        "pressed_before_voice_finished": answered < spoken,
        "number_before": base,
        "biggest_rise": (max(touching) - base) if touching else 0,
        "biggest_drop": (base - min(touching)) if touching else 0,
        "share_without_contact": round(1 - len(touching) / max(1, len(values)), 2),
        "one_value_per_second_from_question_start": [int(statistics.median(per_second[s])) for s in sorted(per_second)],
        "photo": os.path.basename(shot) if os.path.exists(shot) else None,
    }


PROMPT = """You are the examiner in a home-made lie detector video. For each REAL question, guess whether the
answer the person gave was the truth or a lie. Any number of them may be lies, including none or all.

What you have: results.json in the current folder (read it) and the photos it names (open them with Read).
The sensor is a soil moisture fork with two fingers resting on it. It reflects contact, pressure, movement
and skin moisture. It is NOT a validated lie detector. 'calm' entries are obvious questions for comparison.
Contact loss makes a question's numbers unreliable. Do not overstate what a photo or number shows.

Reply with ONLY a JSON array, one object per real question, in order:
[{"number":1,"verdict":"truth" or "lie","confidence":0-100,"reason":"one short plain sentence"}]"""


def judge(results, folder):
    room = tempfile.mkdtemp(prefix="examiner-")  # a clean folder: this Claude knows nothing else
    try:
        with open(os.path.join(room, "results.json"), "w") as f:
            json.dump(results, f, indent=1)
        for r in results:
            if r["photo"]:
                shutil.copy(os.path.join(folder, r["photo"]), room)
        run = subprocess.run(
            ["claude", "-p", PROMPT, "--model", "sonnet", "--tools", "Read", "--allowedTools", "Read",
             "--setting-sources", ""],
            cwd=room, capture_output=True, text=True, timeout=300, stdin=subprocess.DEVNULL)
        with open(os.path.join(folder, "claude-reply.txt"), "w") as f:
            f.write(run.stdout + ("\n--- errors ---\n" + run.stderr if run.stderr else ""))
        found = re.search(r"\[.*\]", run.stdout, re.S)
        verdicts = json.loads(found.group(0))
        assert [v["number"] for v in verdicts] == list(range(1, len(REAL) + 1))
        assert all(v["verdict"] in ("truth", "lie") for v in verdicts)
        return verdicts
    finally:
        shutil.rmtree(room, ignore_errors=True)


def main():
    practice = sys.argv[1:] == ["practice"]
    runs = os.path.join(HERE, "runs")
    os.makedirs(runs, exist_ok=True)
    with open(os.path.join(runs, ".gitignore"), "w") as f:
        f.write("*\n")  # photos of a face never go into git
    folder = os.path.join(runs, time.strftime("%m%d-%H%M%S") + ("-practice" if practice else ""))
    os.makedirs(folder)

    fd = bt.open_port()
    threading.Thread(target=read_serial, args=(fd,), daemon=True).start()
    server = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    webbrowser.open(f"http://127.0.0.1:{server.server_port}/")
    print("The page is open in your browser. Click on it, then follow the screen.")
    print("To stop at any time: Control + C here.")

    show("start", "Press SPACE to start", "PRACTICE" if practice else "The real test. One take.")
    wait_key({"space"})
    os.write(fd, b"o")

    show("touch", "Rest two fingers on the fork")
    count = 0
    while count < 10:
        pause(0.1)
        count = count + 1 if samples and samples[-1][1] > TOUCH_LEVEL else 0

    show("baseline", "Sit still", "Rest your arm on the table and do not move your fingers")
    pause(BASELINE_SECONDS)

    results = []
    plan = [(i, "calm", q) for i, q in enumerate(CALM[:1] if practice else CALM, 1)]
    if not practice:
        plan += [(i, "real", q) for i, q in enumerate(REAL, 1)]
    for number, kind, text in plan:
        results.append(ask(number, kind, text, folder))
        with open(os.path.join(folder, "results.json"), "w") as f:
            json.dump(results, f, indent=1)

    with lock, open(os.path.join(folder, "numbers.csv"), "w") as f:
        f.write("time,value\n" + "".join(f"{t:.2f},{v}\n" for t, v in samples))

    if practice:
        ok = all(r["photo"] for r in results)
        show("done", "Practice finished", "Photo saved" if ok else "The camera photo FAILED")
        print("Practice finished.", "Photo saved." if ok else "The camera photo FAILED.", "Folder:", folder)
        pause(5)
        return

    show("judging", "You can lift your fingers", "Claude is deciding. Keep the paper folded.")
    try:
        verdicts = judge(results, folder)
    except Exception as e:
        show("error", "Claude's answer failed", "Your numbers are saved. Keep the paper folded.")
        print("Judging failed:", repr(e), "\nEverything recorded is in", folder)
        pause(10)
        return

    saved = os.path.join(folder, "verdicts.json")
    with open(saved, "w") as f:
        json.dump({"saved_at": time.strftime("%Y-%m-%d %H:%M:%S"), "verdicts": verdicts}, f, indent=1)
    print("Verdicts SAVED:", saved)

    show("saved", "Claude's guesses are saved", "Keep the paper folded. Press SPACE to see guess 1.")
    wait_key({"space"})
    for v in verdicts:
        lie = v["verdict"] == "lie"
        os.write(fd, b"r" if lie else b"g")
        show("reveal", f"{v['number']}. {'LIE' if lie else 'TRUTH'}",
             f"{REAL[v['number'] - 1]}  ({v['confidence']}% sure) {v['reason']}   [SPACE = next]")
        wait_key({"space"})
    os.write(fd, b"o")
    lies = ", ".join(str(v["number"]) for v in verdicts if v["verdict"] == "lie") or "none"
    show("done", "Now open the paper", f"Claude said LIE for: {lies}")
    wait_key({"space"})


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nStopped.")
