#!/usr/bin/env python3
"""Fetch Furkastrasse Schaffhausen bau-cam latest image / archive metadata.
Credentials are intentionally NOT stored in this script.
Use env vars: BAUCAM_USER, BAUCAM_PASS.
"""
import base64, json, os, re, sys, urllib.request
from pathlib import Path

BASE = "https://bau-cam.ch/schaffhausen/"
UA = "Mozilla/5.0 (X11; Linux x86_64) Hermes ERNE monitor"


def fetch(path_or_url: str) -> tuple[dict, bytes]:
    if path_or_url.startswith("http"):
        url = path_or_url
    else:
        url = BASE + path_or_url.lstrip("/")
    user = os.environ.get("BAUCAM_USER")
    pw = os.environ.get("BAUCAM_PASS")
    if not user or not pw:
        raise SystemExit("Set BAUCAM_USER and BAUCAM_PASS")
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    token = base64.b64encode(f"{user}:{pw}".encode()).decode()
    req.add_header("Authorization", f"Basic {token}")
    with urllib.request.urlopen(req, timeout=30) as r:
        return dict(r.headers), r.read()


def latest(output="/home/agent/erne_furkastrasse_latest.jpg"):
    headers, html = fetch("live.php")
    text = html.decode("utf-8", "replace")
    m = re.search(r"bilder/\d+_TIMING\.jpg", text)
    if not m:
        raise SystemExit("No latest image match found")
    match = m.group(0)
    img_headers, img = fetch(match)
    out = Path(output)
    out.write_bytes(img)
    return {"match": match, "path": str(out), "bytes": len(img), "content_type": img_headers.get("Content-Type") or img_headers.get("content-type")}


def archive():
    headers, html = fetch("archiv.php")
    text = html.decode("utf-8", "replace")
    count_match = re.search(r"Anzahl Bilder\s+(\d+)", text)
    times = re.findall(r"(\d{2}\.\d{2}\.\d{4}\s*/\s*\d{2}\.\d{2}\s*Uhr).*?value=\"(\d+_TIMING\.jpg)\"", text, re.S)
    return {"count": int(count_match.group(1)) if count_match else len(times), "first": times[0] if times else None, "last": times[-1] if times else None, "items": times}


if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "latest"
    if cmd == "latest":
        print(json.dumps(latest(*(sys.argv[2:] or [])), ensure_ascii=False, indent=2))
    elif cmd == "archive":
        data = archive()
        # Keep stdout compact for agent use.
        print(json.dumps({k: data[k] for k in ["count", "first", "last"]}, ensure_ascii=False, indent=2))
    else:
        raise SystemExit("Usage: furkastrasse_webcam_check.py [latest [output.jpg]|archive]")
