"""Tests for the last two components: PHONE REACH (PWA) and the 3D AVATAR.

Coverage:
  1. GET /manifest.webmanifest -> valid JSON with the required PWA keys
  2. GET /sw.js -> JS with a version constant, and API routes are NOT cache-first
  3. GET /phone -> 200 with the four action buttons and the "not telephony" statement
  4. GET /avatar -> 200 and references three.js, with the state indicator
  5. The nav includes Phone and Avatar on every page
  6. The mobile CSS block exists (<=640px) in the stylesheet
  7. both components are registered as `tool` components and audited through audit.record()
"""

from __future__ import annotations

import json
import os
import tempfile

import pytest

_TMP = tempfile.mkdtemp(prefix="jarvis-pwa-test-")
os.environ["JARVIS_DB"] = os.path.join(_TMP, "test.db")
os.environ["JARVIS_MEMORY_DB"] = os.path.join(_TMP, "data", "jarvis.db")

from orchestrator import audit  # noqa: E402
from orchestrator import avatar  # noqa: E402
from orchestrator import memory  # noqa: E402
from orchestrator import pwa  # noqa: E402
from orchestrator import scheduling  # noqa: E402
from orchestrator.components import register_default_components  # noqa: E402
from orchestrator.db import init_db  # noqa: E402
from orchestrator.registry import REGISTRY  # noqa: E402

APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

#: Every page that carries the shared nav. (error.html is the 404 shell.)
NAV_PAGES = [
    "/",
    "/senses",
    "/opportunities",
    "/ui/verification",
    "/bots",
    "/measurement",
    "/memory",
    "/schedules",
    "/voice",
    "/audit",
    "/phone",
    "/avatar",
]


@pytest.fixture(autouse=True)
def fresh_db():
    db = os.environ["JARVIS_DB"]
    for suffix in ("", "-wal", "-shm"):
        try:
            os.remove(db + suffix)
        except FileNotFoundError:
            pass
    init_db()
    audit.init_db()
    memory.init_db()
    scheduling.init_db()
    REGISTRY.clear()
    register_default_components(REGISTRY)
    pwa.register_phone_reach(REGISTRY)
    avatar.register_avatar(REGISTRY)
    yield
    REGISTRY.clear()
    register_default_components(REGISTRY)


@pytest.fixture
def client():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        yield c


# --------------------------------------------------------------------------
# 1. manifest
# --------------------------------------------------------------------------

def test_manifest_is_valid_json_with_required_keys(client):
    res = client.get("/manifest.webmanifest")
    assert res.status_code == 200
    body = json.loads(res.get_data(as_text=True))
    for key in ("name", "short_name", "start_url", "display", "background_color",
                "theme_color", "icons"):
        assert key in body, f"manifest is missing {key}"
    assert body["name"] == "JARVIS"
    assert body["short_name"] == "JARVIS"
    assert body["start_url"] == "/"
    assert body["display"] == "standalone"
    assert body["background_color"].startswith("#")
    assert body["theme_color"].startswith("#")
    assert body["background_color"] == body["theme_color"] == pwa.BACKGROUND_COLOR


def test_manifest_icons_exist_on_disk_and_are_png(client):
    body = json.loads(client.get("/manifest.webmanifest").get_data(as_text=True))
    sizes = {i["sizes"] for i in body["icons"]}
    assert {"192x192", "512x512"} <= sizes
    for icon in body["icons"]:
        assert icon["type"] == "image/png"
        path = os.path.join(APP_DIR, icon["src"].lstrip("/"))
        assert os.path.exists(path), f"missing icon file {path}"
        with open(path, "rb") as fh:
            assert fh.read(8) == b"\x89PNG\r\n\x1a\n", "icon is not a real PNG"


@pytest.mark.parametrize("size", [192, 512])
def test_icon_route_serves_an_image(client, size):
    res = client.get(f"/static/icons/icon-{size}.png")
    assert res.status_code == 200
    assert res.headers["Content-Type"].startswith("image/png")


def test_manifest_has_its_own_content_type(client):
    res = client.get("/manifest.webmanifest")
    assert "manifest" in res.headers["Content-Type"] or "json" in res.headers["Content-Type"]


# --------------------------------------------------------------------------
# 2. service worker
# --------------------------------------------------------------------------

def test_service_worker_returns_js_with_a_version_constant(client):
    res = client.get("/sw.js")
    assert res.status_code == 200
    assert "javascript" in res.headers["Content-Type"]
    js = res.get_data(as_text=True)
    assert "const CACHE_VERSION = '" in js
    assert pwa.CACHE_VERSION in js
    assert "caches.open" in js
    assert "addEventListener('install'" in js
    assert "addEventListener('fetch'" in js


def test_service_worker_is_not_cache_first_for_api_routes(client):
    js = client.get("/sw.js").get_data(as_text=True)
    # the API branch must be the network-first path with NO cache read/fallback
    assert "async function apiNetworkFirst" in js
    api_body = js.split("async function apiNetworkFirst", 1)[1].split("async function", 1)[0]
    assert "caches.match" not in api_body
    assert "cache.match" not in api_body
    assert "cache.put" not in api_body
    assert "return await fetch(request)" in api_body
    # and the API list must be dispatched to that branch, before the static branch
    fetch_handler = js.split("self.addEventListener('fetch'", 1)[1]
    assert fetch_handler.index("isApi(url)") < fetch_handler.index("'/static/'")
    assert "apiNetworkFirst(request)" in fetch_handler


def test_service_worker_caches_static_but_not_api(client):
    js = client.get("/sw.js").get_data(as_text=True)
    static_body = js.split("async function staticCacheFirst", 1)[1].split("async function", 1)[0]
    assert "cache.match" in static_body
    assert "cache.put" in static_body
    # API list contains the JSON routes, and is declared as never cached
    assert "/api/" in js
    assert "/audit/verify" in js


# --------------------------------------------------------------------------
# 3. /phone
# --------------------------------------------------------------------------

def test_phone_page_returns_200_with_action_buttons(client):
    res = client.get("/phone")
    assert res.status_code == 200
    html = res.get_data(as_text=True)
    for action in pwa.PHONE_ACTIONS:
        assert f'data-action="{action}"' in html, f"missing {action} button"
    for label in pwa.ACTION_LABELS.values():
        assert label in html, f"missing label {label}"
    # the live numbers are on the page
    assert "Loop counts" in html
    assert "Audit chain" in html
    # the add-to-home-screen instructions
    assert "Add to home screen" in html
    assert "Add to Home Screen" in html
    assert "Install app" in html


def test_phone_page_states_plainly_it_is_not_telephony(client):
    html = client.get("/phone").get_data(as_text=True)
    low = html.lower()
    assert "not real telephony" in low
    assert "pwa" in low
    assert "no sms" in low
    assert "no phone number" in low
    assert "twilio" in low


def test_phone_action_writes_one_audit_row(client):
    before = audit.verify()["length"]
    res = client.post("/phone/action", data={"action": "tick"}, follow_redirects=False)
    assert res.status_code in (302, 303)
    rows = audit.recent(limit=1, actor=pwa.COMPONENT_NAME, action="phone.action")
    assert rows, "phone action wrote no audit row"
    assert rows[0]["payload"]["action"] == "tick"
    assert rows[0]["payload"]["telephony"] is False
    # the action itself also writes its own rows (scheduling.tick() audits its tick),
    # so the phone must add at least the one phone.action row on top.
    assert audit.verify()["length"] >= before + 1


def test_phone_unknown_action_is_refused_and_audited(client):
    client.post("/phone/action", data={"action": "call-mum"})
    refused = [r for r in audit.recent(limit=5, actor=pwa.COMPONENT_NAME)
               if r["payload"].get("status") == "refused"]
    assert refused, "a refused phone action must still be audited"


def test_phone_api_reports_no_telephony(client):
    body = client.get("/api/phone").get_json()
    assert body["real_telephony"] is False
    assert body["phone_number"] is None
    assert body["sms"] is False
    assert body["calls"] is False
    assert [a["action"] for a in body["actions"]] == list(pwa.PHONE_ACTIONS)


# --------------------------------------------------------------------------
# 4. /avatar
# --------------------------------------------------------------------------

def test_avatar_page_returns_200_and_references_three(client):
    res = client.get("/avatar")
    assert res.status_code == 200
    html = res.get_data(as_text=True)
    assert "three" in html.lower()
    assert avatar.THREE_CDN in html
    assert 'type="importmap"' in html
    assert "THREE_VERSION" not in html  # the constant was rendered, not left raw
    assert avatar.THREE_VERSION in html


def test_avatar_page_has_the_state_indicator_and_force_buttons(client):
    html = client.get("/avatar").get_data(as_text=True)
    assert 'id="statelabel"' in html
    for state in avatar.STATES:
        assert f'data-state="{state}"' in html
        assert f'id="btn-{state}"' in html


def test_avatar_page_has_a_webgl_fallback(client):
    html = client.get("/avatar").get_data(as_text=True)
    assert 'id="fallback"' in html
    assert "WebGL is not available" in html


def test_avatar_page_is_honest_about_not_being_cognition(client):
    html = client.get("/avatar").get_data(as_text=True)
    low = html.lower()
    assert "not a model of the system" in low
    assert "not sentient" in low
    assert "does not represent" in low or "visual front door" in low


def test_dashboard_links_to_the_front_door(client):
    html = client.get("/").get_data(as_text=True)
    assert 'href="/avatar"' in html
    assert "FRONT DOOR" in html.upper()


def test_avatar_state_is_audited(client):
    res = client.post("/avatar/state", json={"state": "listening", "detail": "test"})
    assert res.status_code == 200
    body = res.get_json()
    assert body["state"] == "LISTENING"
    assert body["visualises_cognition"] is False
    rows = avatar.recent_states(limit=5)
    assert rows and rows[0]["subject_id"] == "LISTENING"


def test_avatar_state_rejects_unknown_state(client):
    res = client.post("/avatar/state", json={"state": "SENTIENT"})
    assert res.status_code == 400
    assert res.get_json()["error"]


# --------------------------------------------------------------------------
# 5. nav on every page
# --------------------------------------------------------------------------

@pytest.mark.parametrize("path", NAV_PAGES)
def test_nav_includes_phone_and_avatar(client, path):
    res = client.get(path)
    assert res.status_code == 200, f"{path} -> {res.status_code}"
    html = res.get_data(as_text=True)
    assert 'href="/phone"' in html, f"{path} nav has no Phone link"
    assert 'href="/avatar"' in html, f"{path} nav has no Avatar link"


@pytest.mark.parametrize("path", ["/", "/phone", "/avatar", "/voice"])
def test_pages_link_the_manifest_and_register_the_sw(client, path):
    html = client.get(path).get_data(as_text=True)
    assert 'rel="manifest"' in html
    assert "/manifest.webmanifest" in html
    assert "serviceWorker" in html
    assert "/sw.js" in html


# --------------------------------------------------------------------------
# 6. the mobile CSS pass
# --------------------------------------------------------------------------

def test_mobile_css_block_exists():
    css = open(os.path.join(APP_DIR, "static", "css", "jarvis.css"), encoding="utf-8").read()
    assert "@media (max-width: 640px)" in css
    # nav -> horizontal scroll strip
    assert "overflow-x: auto" in css
    assert "white-space: nowrap" in css
    # tables -> labelled cards from data-label attributes
    assert "attr(data-label)" in css
    assert "table thead { display: none" in css
    # buttons -> full-width and thumb-sized
    assert "min-height: 46px" in css
    assert "width: 100%" in css


@pytest.mark.parametrize("path", ["/", "/phone", "/audit"])
def test_tables_carry_data_labels(client, path):
    html = client.get(path).get_data(as_text=True)
    assert "data-label=" in html
    assert 'href="/static/css/jarvis.css"' in html


# --------------------------------------------------------------------------
# 7. registry + audit integration
# --------------------------------------------------------------------------

def test_both_components_are_registered_as_tools():
    names = {c["name"]: c for c in REGISTRY.describe()}
    assert pwa.COMPONENT_NAME in names
    assert avatar.COMPONENT_NAME in names
    assert names[pwa.COMPONENT_NAME]["kind"] == "tool"
    assert names[avatar.COMPONENT_NAME]["kind"] == "tool"
    assert names[pwa.COMPONENT_NAME]["handles_state"] is None
    assert names[avatar.COMPONENT_NAME]["handles_state"] is None


def test_registration_is_idempotent():
    before = len(REGISTRY.describe())
    pwa.register_phone_reach(REGISTRY)
    avatar.register_avatar(REGISTRY)
    assert len(REGISTRY.describe()) == before


def test_components_document_what_they_are_not():
    phone = pwa.describe()
    assert phone["real_telephony"] is False
    assert phone["api_cached"] is False
    face = avatar.describe()
    assert face["visualises_cognition"] is False
    assert face["sentient"] is False
    assert face["states"] == list(avatar.STATES)


# --------------------------------------------------------------------------
# 4b. the force-state precedence rule (the one real avatar bug)
# --------------------------------------------------------------------------

def _avatar_module_js() -> str:
    """The inline <script type="module"> of the avatar page, Jinja rendered."""
    import re
    from flask import Flask
    import app as app_module

    flask_app = app_module.create_app() if hasattr(app_module, "create_app") else None
    if flask_app is None:
        flask_app = app_module.app
    with flask_app.test_client() as c:
        html = c.get("/avatar").get_data(as_text=True)
    m = re.search(r'<script type="module">(.*?)</script>', html, re.S)
    assert m, "avatar page has no module script"
    return m.group(1)


def test_force_state_outranks_event_state():
    """A user-pinned state must win over any event-derived state.

    The precedence lives in the page's `resolveState(forced, evented)` so it can
    be executed directly: a force button must hold on a browser with no speech
    voice and no speech recognition, where no real event ever fires.
    """
    import json
    import re
    import shutil
    import subprocess

    node = shutil.which("node")
    if not node:
        pytest.skip("node is not available to execute the page's state resolver")

    js = _avatar_module_js()
    m = re.search(r"function resolveState\([^)]*\)\s*\{.*?\n\}", js, re.S)
    assert m, "the avatar page has no resolveState(forced, evented) precedence function"
    fn = m.group(0)

    # The renderer must derive what it paints from that one rule.
    assert "resolveState(forcedState, eventState)" in js, (
        "renderState() must paint resolveState(forcedState, eventState)"
    )

    cases = [
        # (forced, evented, expected) — a pin always wins
        ("SPEAKING", "IDLE", "SPEAKING"),
        ("LISTENING", "THINKING", "LISTENING"),
        ("THINKING", "IDLE", "THINKING"),
        ("IDLE", "SPEAKING", "IDLE"),
        # no pin -> the real event shows
        (None, "SPEAKING", "SPEAKING"),
        (None, "LISTENING", "LISTENING"),
        # nothing at all -> IDLE
        (None, None, "IDLE"),
        (None, "IDLE", "IDLE"),
    ]
    script = fn + "\nconst cases = " + json.dumps(cases) + ";\n" + (
        "const out = cases.map(([f, e, want]) => "
        "[f, e, want, resolveState(f, e)]);\n"
        "console.log(JSON.stringify(out));\n"
    )
    res = subprocess.run([node, "-e", script], capture_output=True, text=True, timeout=30)
    assert res.returncode == 0, res.stderr
    rows = json.loads(res.stdout.strip().splitlines()[-1])
    for forced, evented, want, got in rows:
        assert got == want, f"resolveState({forced!r}, {evented!r}) -> {got!r}, expected {want!r}"

    # A force click must invalidate in-flight utterance handlers, and an error
    # before an utterance ever started must not clear the pin.
    assert "utteranceToken" in js, "force clicks must invalidate in-flight utterance handlers"
    assert "if (!started)" in js, "a pre-start utterance error must not clear a forced state"
