#!/usr/bin/env python3
"""door_watch.py — Project Doorman trigger: when Object Analytics on the front
P4708 reports a NEW person-at-porch (ACC_OptimizedAction) event, announce it on
the Google/Nest speakers. Debounced, quiet-hours gated, pointer-based (survives
restart). Runs autonomously; attracts/rings on the next real visitor."""
import json, os, re, subprocess, time, datetime as dt
from pathlib import Path

ALLOW_ANNOUNCE = os.environ.get("DOOR_ANNOUNCE", "0") == "1"   # OFF by default: log-only

BASE = Path(__file__).resolve().parent
CREDS = Path(r"C:\Users\DEMO - JARVIS\AppData\Local\hermes\axis_creds.json")
PTR   = BASE / "door_pointer.txt"

POLL    = 10          # seconds between camera polls
COOLDOWN= 120         # min between announces (a lingering visitor doesn't re-ring)
QUIET_START, QUIET_END = 8, 21   # local announce window (like delivery)
IMPORT = True

if IMPORT:
    import sys; sys.path.insert(0, str(BASE))
    from door_announce import announce, CLOUD

def cam_creds():
    js = json.load(open(CREDS, encoding="utf-8"))
    f = js["cameras"]["corner_front"]          # P4708 .179 = doorman video
    return f["ip"], f["user"], f["pass"]

def fetch(ip, u, p):
    out = subprocess.run(["curl", "-s", "--anyauth", "-u", f"{u}:{p}", "--max-time", "20",
                          f"http://{ip}/axis-cgi/record/list.cgi?&count=120"],
                         capture_output=True, text=True).stdout
    rows = []
    for tag in re.findall(r"<recording[^>]*>", out):
        rid = re.search(r'recordingid="([^"]*)"', tag)
        tr  = re.search(r'eventtrigger="([^"]*)"', tag)
        st  = re.search(r'starttime="([^"]*)"', tag)
        if rid and tr:
            rows.append({"rid": rid.group(1), "trig": tr.group(1),
                         "t": (st.group(1) if st else "")})
    return rows

def in_window():
    h = dt.datetime.now().hour
    return QUIET_START <= h < QUIET_END

def last_pointer():
    try:
        return open(PTR).read().strip()
    except Exception:
        return ""

def points_to_announce(rows, pointer):
    """New ACC_OptimizedAction events with starttime > pointer -> announce once."""
    new = []
    for r in rows:
        if r["trig"] != "ACC_OptimizedAction":
            continue
        t = r["t"]
        if t > pointer:
            new.append((t, r["rid"]))
    if not new:
        return pointer, False
    new.sort()
    last_t, last_rid = new[-1]
    return last_t, True

def main():
    ip, u, p = cam_creds()
    state = {"ptr": last_pointer(), "last": 0}
    print("door_watch up — watching %s for people at the front door (cloud voice; my voice pending firewall)" % ip, flush=True)
    while True:
        try:
            rows = fetch(ip, u, p)
            if rows:
                if not state["ptr"]:
                    mts = [r["t"] for r in rows if r["trig"] == "ACC_OptimizedAction"]
                    if mts:
                        state["ptr"] = max(mts)      # seed: don't replay history, ring on NEW only
                ptr, ring = points_to_announce(rows, state["ptr"])
                if ptr > state["ptr"]:
                    state["ptr"] = ptr
                if ring:
                    if not in_window():
                        print("door event outside %02d-%02d window — suppressed" % (QUIET_START, QUIET_END), flush=True)
                    elif time.time() - state["last"] < COOLDOWN:
                        print("door event within cooldown — skipped", flush=True)
                    elif ALLOW_ANNOUNCE:
                        print("DOOR VISITOR — announcing", flush=True)
                        state["last"] = time.time()
                        announce(CLOUD)
                    else:
                        state["last"] = time.time()
                        print("door event — LOG ONLY (announce OFF): would say 'Someone is at the front door'", flush=True)
                open(PTR, "w").write(state["ptr"])
        except Exception as e:
            print("poll error:", e, flush=True)
        time.sleep(POLL)

if __name__ == "__main__":
    main()
