#!/usr/bin/env python3
"""door_announce.py — announce a front-door visitor on the Google/Nest speakers.

Reusable by Project Doorman: when someone's at the door (AOA person-in-porch,
or the doorman trigger), cast a pre-generated Jarvis-voice clip
("Someone is at the front door.") to the Nest Wifi speaker points so Phil can
walk over and take it. Pre-cached clip — costs no TTS quota per fire.

Usage:
  python3 door_announce.py            # discover + cast to the speakers
  python3 door_announce.py --check   # serve the clip + verify it's reachable (no sound)
"""
import os, sys, threading, time, urllib.parse, pychromecast
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

BASE  = os.path.dirname(os.path.abspath(__file__))
CLIP  = os.path.join(BASE, "door_announce.mp3")
TEXT  = "Someone is at the front door."
CLOUD = ("https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=en&q="
         + urllib.parse.quote(TEXT))   # no firewall needed — speaker fetches from the internet
LAN   = "192.168.1.68"        # Lenovo on the home LAN (Nest points reach this)
TAIL  = "100.108.59.81"       # Tailscale for away/home reachability
PORT  = 8399                  # same port the delivery announce holds
TARGETS = ["Kitchen", "Dining", "living"]   # Nest Wifi speaker friendly-name substrings

def _serve(port):
    class H(BaseHTTPRequestHandler):
        clip = open(CLIP, "rb").read()
        def do_GET(self):
            if "door" in self.path:
                b = self.clip
                self.send_response(200); self.send_header("Content-Type", "audio/mpeg")
                self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
            else:
                self.send_response(404); self.end_headers()
        def log_message(self, *a):
            pass
    srv = ThreadingHTTPServer(("0.0.0.0", port), H)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    return srv

def announce(url):
    ccs, _ = pychromecast.get_chromecasts(timeout=8)
    hits = [c for c in ccs if any(t in c.cast_info.friendly_name for t in TARGETS)]
    if not hits:
        print("no speaker targets found (have: %s)"
              % ", ".join(c.cast_info.friendly_name for c in ccs)); return False
    for c in hits:
        try:
            c.wait(timeout=10)
            mc = c.media_controller
            mc.play_media(url, "audio/mpeg"); mc.block_until_active(timeout=20)
            print("  announced on", c.cast_info.friendly_name)
        except Exception as e:
            print("  cast fail on", c.cast_info.friendly_name, "-", e)
    return True

if __name__ == "__main__":
    if "--cloud" in sys.argv:
        print("casting cloud voice (no firewall):", CLOUD)
        announce(CLOUD); sys.exit(0)
    srv = _serve(PORT)
    url = "http://%s:%d/door_announce.mp3" % (LAN, PORT)
    time.sleep(0.4)
    if "--check" in sys.argv:
        import urllib.request
        try:
            r = urllib.request.urlopen("http://%s:%d/door_announce.mp3" % (LAN, PORT), timeout=5)
            print("READY: clip served %d bytes on %s (LAN). Speaker fetch depends on the firewall allow." % (r.status, url))
        except Exception as e:
            print("check failed:", e)
        sys.exit(0)
    print("casting", url)
    announce(url)
    time.sleep(2)
