#!/usr/bin/env python3
"""Browser entrypoint for the SAME Sofia agent — for fast iteration without phoning in.

Reuses bot.run_agent (identical prompt, model, voice, booking + hang-up logic) but over a
browser WebRTC transport via Pipecat's dev runner. Serves a mic UI at http://localhost:7860.

Caveat: this path is 16 kHz WebRTC, NOT 8 kHz telephony — great for testing conversation /
prompt / voice / hang-up, but it does NOT reproduce phone-specific audio (µ-law, clipping,
VAD-on-8kHz). Appointment capture to Odoo is OFF here (do_capture=False) so browser tests
don't create CRM cards.

Run:
    ./run_web.sh         # then open http://localhost:7860, click Connect, allow mic, talk
"""

from pipecat.runner.utils import create_transport
from pipecat.transports.base_transport import TransportParams

from bot import run_agent


import os

# Browser tests don't write to Odoo by default (keeps test bookings out of the CRM). Set
# WEB_ALLOW_CAPTURE=true for a one-off test that actually creates the lead.
WEB_ALLOW_CAPTURE = os.environ.get("WEB_ALLOW_CAPTURE", "false").lower() in ("1", "true", "yes")


async def bot(runner_args):
    """Called by pipecat.runner.run.main for each browser connection."""
    transport = await create_transport(
        runner_args,
        {"webrtc": lambda: TransportParams(audio_in_enabled=True, audio_out_enabled=True)},
    )
    await run_agent(transport, do_capture=WEB_ALLOW_CAPTURE)


if __name__ == "__main__":
    import os
    import sys

    import uvicorn

    # Serve on the LAN over HTTPS so the mic works from another machine (browsers require
    # a secure context off-localhost). Reuses the self-signed certs (valid for 10.10.1.221).
    CERT = os.environ.get("WEB_CERT", "/home/tocmo0nlord/pipecat-run/certs/cert.pem")
    KEY = os.environ.get("WEB_KEY", "/home/tocmo0nlord/pipecat-run/certs/key.pem")
    if os.path.exists(CERT) and os.path.exists(KEY):
        _orig_run = uvicorn.run

        def _run_with_tls(app, *args, **kwargs):
            kwargs.setdefault("ssl_certfile", CERT)
            kwargs.setdefault("ssl_keyfile", KEY)
            return _orig_run(app, *args, **kwargs)

        uvicorn.run = _run_with_tls
        if "--host" not in sys.argv:
            sys.argv += ["--host", "0.0.0.0"]
        print("Browser UI: https://10.10.1.221:7860  (accept the self-signed cert once)")

    from pipecat.runner.run import main

    main()
