"""PHONE REACH — the installable PWA shell for the control panel.

What this is
------------
A *progressive web app* wrapper around the pages that already exist. Adding a
manifest, a service worker, a generated icon set and one mobile-only stylesheet
lets the SAME Flask app be installed on a phone home screen and driven one-handed
through ``GET /phone``.

What this is NOT
----------------
Telephony. There is **no phone number, no SMS, no voice call and no carrier or
Twilio integration** anywhere in this build. Nothing here can dial, text or
receive a call: the browser reaches this Flask server over HTTPS, exactly like
the desktop pages. Real telephony (Twilio or similar) is a separate future task
and is deliberately not built.

Design notes
------------
* The manifest and the service worker are generated from the constants below so
  the cache name, the shell list and the API list can never drift apart.
* ``CACHE_VERSION`` is the cache-busting constant: change it and every client
  throws its old shell away on the next activate. Pages are network-first (a
  stale page is worse than no page in a control panel); static assets are
  cache-first; API routes are network-only, so data is never served from cache.
* Icons are drawn programmatically with Pillow when it is installed. If Pillow
  is missing the module falls back to an SVG icon and says so — it never
  pretends a PNG exists.
* Every phone action goes through the modules that already exist (scheduler,
  ingestion, bot factory, voice) and then writes ONE extra audit row naming the
  phone as the origin, through ``orchestrator.audit.record()``.
"""

from __future__ import annotations

import json
import logging
import os

from . import audit
from .errors import OrchestratorError, ValidationError

log = logging.getLogger("jarvis.pwa")

COMPONENT_NAME = "PhoneReach"

#: Cache-busting constant. Bump it and every installed client drops its shell.
CACHE_VERSION = "jarvis-shell-v1"
CACHE_PREFIX = "jarvis-shell"

APP_NAME = "JARVIS"
SHORT_NAME = "JARVIS"
DISPLAY = "standalone"
START_URL = "/"
SCOPE = "/"

#: Matches --bg in every template; the phone shell must not flash white.
BACKGROUND_COLOR = "#0b0d10"
THEME_COLOR = "#0b0d10"
ACCENT_COLOR = "#5eead4"

MANIFEST_URL = "/manifest.webmanifest"
SW_URL = "/sw.js"
ICON_URL_DIR = "/static/icons"
ICON_SIZES = (192, 512)
ICON_DIR = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "static", "icons"
)
MOBILE_CSS = "/static/css/jarvis.css"

#: The app shell: the pages a phone needs to open with no network at all.
SHELL_PAGES = (
    "/",
    "/phone",
    "/avatar",
    "/senses",
    "/opportunities",
    "/bots",
    "/measurement",
    "/memory",
    "/ui/verification",
    "/schedules",
    "/voice",
    "/audit",
)

#: Static assets precached with the shell.
SHELL_STATIC = (
    MOBILE_CSS,
    "/static/icons/icon-192.png",
    "/static/icons/icon-512.png",
)

#: JSON routes. These are NEVER cached: network-first with no cache fallback,
#: so the phone can never show yesterday's chain status as if it were current.
API_PREFIXES = (
    "/api/",
    "/audit/verify",
    "/audit/ledger",
    "/audit/status",
    "/audit/rows",
    "/audit/trace",
    "/audit/tamper-test",
    "/audit/_tamper",
    "/health",
    "/events",
    "/jobs",
    "/signals",
    "/components",
    "/states",
    "/verification/",
    "/measurement/rules",
    "/opportunities/rules",
    "/opportunities/rejections",
    "/opportunities/runs",
    "/ingest",
)

HONESTY = (
    "This is a PWA (progressive web app) over HTTPS, NOT real telephony. There is no phone "
    "number, no SMS and no voice call: nothing here can dial, text or ring. The browser talks "
    "to this same Flask server over HTTPS, and the service worker only caches the pages you "
    "already loaded so the panel opens offline. Real telephony (Twilio or similar) is a separate "
    "future task and is NOT built."
)

#: The four one-tap actions on the phone home screen.
PHONE_ACTIONS = ("tick", "fetch", "build", "speak")

ACTION_LABELS = {
    "tick": "Run tick",
    "fetch": "Fetch signals",
    "build": "Build bot",
    "speak": "Speak",
}

ACTION_DESCRIPTIONS = {
    "tick": "Fire exactly one scheduler tick (no daemon runs in the background).",
    "fetch": "Real HTTP fetch of every configured source, stored and audited.",
    "build": "Build a deterministic bot spec from a VERIFIED opportunity.",
    "speak": "Build the loop-status sentence and speak it with the browser's speechSynthesis.",
}


# --------------------------------------------------------------------------
# icons — generated, never hand-waved
# --------------------------------------------------------------------------

def _draw_icon(size: int):
    """A dark square with a cyan glyph: an eye/core ring with a bright pupil."""
    from PIL import Image, ImageDraw

    scale = 4  # draw big, downsample: cheap antialiasing
    s = size * scale
    img = Image.new("RGB", (s, s), (11, 13, 16))
    d = ImageDraw.Draw(img)

    # inner plate + hairline border (same --line colour as the pages)
    pad = int(s * 0.04)
    d.rounded_rectangle([pad, pad, s - pad, s - pad], radius=int(s * 0.16),
                        outline=(36, 42, 51), width=max(1, int(s * 0.012)))

    cx = cy = s / 2
    cyan = (94, 234, 212)

    # outer ring
    r_out = s * 0.29
    w = int(s * 0.045)
    d.ellipse([cx - r_out, cy - r_out, cx + r_out, cy + r_out], outline=cyan, width=w)

    # glyph: a vertical bar (the "spine") plus the bright core
    bar_w = int(s * 0.055)
    d.rounded_rectangle([cx - bar_w / 2, cy - r_out * 1.35, cx + bar_w / 2, cy - r_out * 0.62],
                        radius=bar_w / 2, fill=cyan)

    r_core = s * 0.075
    d.ellipse([cx - r_core, cy - r_core, cx + r_core, cy + r_core], fill=(190, 255, 245))

    # two ticks, so the mark reads at 48px as well as 512px
    tw = int(s * 0.02)
    for dx in (-1, 1):
        d.rounded_rectangle([cx + dx * r_out * 1.45 - (tw if dx < 0 else 0),
                             cy - s * 0.10,
                             cx + dx * r_out * 1.45 + (tw if dx > 0 else 0),
                             cy + s * 0.10], radius=tw, fill=(45, 120, 112))

    return img.resize((size, size), Image.LANCZOS)


def _draw_svg(size: int) -> str:
    """Fallback glyph when Pillow is not installed. Honest, small, valid SVG."""
    return (
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{size}" height="{size}" '
        f'viewBox="0 0 100 100" role="img" aria-label="JARVIS">'
        f'<rect width="100" height="100" rx="16" fill="{BACKGROUND_COLOR}"/>'
        f'<rect x="3" y="3" width="94" height="94" rx="14" fill="none" stroke="#242a33"/>'
        f'<circle cx="50" cy="50" r="27" fill="none" stroke="{ACCENT_COLOR}" stroke-width="4"/>'
        f'<rect x="47" y="15" width="6" height="18" rx="3" fill="{ACCENT_COLOR}"/>'
        f'<circle cx="50" cy="50" r="7" fill="#befff5"/>'
        f"</svg>"
    )


def ensure_icons() -> dict:
    """Create static/icons/icon-192.png + icon-512.png if they are missing.

    Returns ``{mode, generated, icons, engine}``. ``mode`` is ``"png"`` when a
    real Pillow-rendered PNG set exists, or ``"svg"`` when Pillow is unavailable
    and the manifest is served with the SVG fallback instead.
    """
    os.makedirs(ICON_DIR, exist_ok=True)
    pngs = {size: os.path.join(ICON_DIR, f"icon-{size}.png") for size in ICON_SIZES}
    have_all = all(os.path.exists(p) and os.path.getsize(p) > 0 for p in pngs.values())
    if have_all:
        return {"mode": "png", "generated": False, "engine": "Pillow",
                "icons": [f"{ICON_URL_DIR}/icon-{s}.png" for s in ICON_SIZES]}

    try:
        for size, path in pngs.items():
            _draw_icon(size).save(path, format="PNG", optimize=True)
        log.info("generated PWA icons: %s", ", ".join(os.path.basename(p) for p in pngs.values()))
        return {"mode": "png", "generated": True, "engine": "Pillow",
                "icons": [f"{ICON_URL_DIR}/icon-{s}.png" for s in ICON_SIZES]}
    except Exception as exc:  # pragma: no cover - Pillow missing in a bare install
        log.warning("Pillow unavailable (%s); falling back to an SVG icon", exc)

    svg_path = os.path.join(ICON_DIR, "icon.svg")
    with open(svg_path, "w", encoding="utf-8") as fh:
        fh.write(_draw_svg(512))
    return {"mode": "svg", "generated": True, "engine": "SVG fallback",
            "icons": [f"{ICON_URL_DIR}/icon.svg"],
            "note": "Pillow is not installed, so the icons are SVG, not PNG."}


def icons_supported() -> bool:
    """True when a real PNG icon set exists (Pillow rendered it)."""
    return all(os.path.exists(os.path.join(ICON_DIR, f"icon-{s}.png")) for s in ICON_SIZES)


# --------------------------------------------------------------------------
# manifest
# --------------------------------------------------------------------------

def manifest() -> dict:
    """The web app manifest, built from the constants above."""
    if icons_supported():
        icons = [
            {"src": f"{ICON_URL_DIR}/icon-{s}.png", "sizes": f"{s}x{s}",
             "type": "image/png", "purpose": "any"}
            for s in ICON_SIZES
        ]
    else:  # pragma: no cover - only when Pillow is missing
        icons = [{"src": f"{ICON_URL_DIR}/icon.svg", "sizes": "any",
                  "type": "image/svg+xml", "purpose": "any"}]
    return {
        "id": START_URL,
        "name": APP_NAME,
        "short_name": SHORT_NAME,
        "description": (
            "JARVIS control panel: the orchestration loop, the audit chain and the "
            "front-door avatar, installable on a phone."
        ),
        "start_url": START_URL,
        "scope": SCOPE,
        "display": DISPLAY,
        "display_override": [DISPLAY, "minimal-ui"],
        "orientation": "portrait-primary",
        "background_color": BACKGROUND_COLOR,
        "theme_color": THEME_COLOR,
        "lang": "en",
        "categories": ["productivity", "utilities"],
        "icons": icons,
    }


def manifest_json() -> str:
    return json.dumps(manifest(), indent=2, sort_keys=False) + "\n"


# --------------------------------------------------------------------------
# service worker
# --------------------------------------------------------------------------

def service_worker_js() -> str:
    """The generated service worker.

    Precedence inside ``fetch``:

    1. ``API_PREFIXES``           -> network-only (no cache read, no cache write)
    2. ``/static/``               -> cache-first, then network, then fill the cache
    3. navigations (pages)        -> network-first, cached shell only as offline fallback
    4. anything else              -> straight to the network

    Pages are intentionally NOT cache-first: this panel shows live counts and a
    hash-chain verdict, and a stale page would be a lie.
    """
    shell = json.dumps(list(SHELL_PAGES + SHELL_STATIC), indent=2)
    api = json.dumps(list(API_PREFIXES), indent=2)
    return f"""/* JARVIS service worker — generated by orchestrator/pwa.py. Do not edit by hand. */
const CACHE_VERSION = '{CACHE_VERSION}';
const CACHE_NAME = '{CACHE_PREFIX}-' + CACHE_VERSION;
const SHELL_ASSETS = {shell};
const API_PREFIXES = {api};

self.addEventListener('install', (event) => {{
  event.waitUntil((async () => {{
    const cache = await caches.open(CACHE_NAME);
    // Reload from the network for every precache entry: the server sends
    // no-store, and a stale shell must never be installed.
    await Promise.all(SHELL_ASSETS.map(async (url) => {{
      try {{
        const res = await fetch(url, {{ cache: 'reload', credentials: 'same-origin' }});
        if (res && res.ok) await cache.put(url, res.clone());
      }} catch (err) {{
        /* one unreachable asset must not abort the install */
      }}
    }}));
    await self.skipWaiting();
  }})());
}});

self.addEventListener('activate', (event) => {{
  event.waitUntil((async () => {{
    const names = await caches.keys();
    await Promise.all(names.map((name) => {{
      if (name.startsWith('{CACHE_PREFIX}-') && name !== CACHE_NAME) return caches.delete(name);
      return null;
    }}));
    await self.clients.claim();
  }})());
}});

function isApi(url) {{
  return API_PREFIXES.some((p) => url.pathname === p || url.pathname.startsWith(p));
}}

// API route: NETWORK-FIRST, and there is deliberately NO cache fallback.
// Data is never stale: if the network is gone, the phone is told so.
async function apiNetworkFirst(request) {{
  try {{
    return await fetch(request);
  }} catch (err) {{
    return new Response(
      JSON.stringify({{
        error: 'offline',
        message: 'the phone is offline; API data is never served from cache, so there is nothing current to show'
      }}),
      {{ status: 503, headers: {{ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }} }}
    );
  }}
}}

// Static asset: CACHE-FIRST, then network (and remember the new copy).
async function staticCacheFirst(request) {{
  const cache = await caches.open(CACHE_NAME);
  const hit = await cache.match(request);
  if (hit) return hit;
  const res = await fetch(request);
  if (res && res.ok) cache.put(request, res.clone());
  return res;
}}

// Page: NETWORK-FIRST (live counts must never be stale), cached shell when offline.
async function pageNetworkFirst(request) {{
  const cache = await caches.open(CACHE_NAME);
  try {{
    const res = await fetch(request);
    if (res && res.ok) cache.put(request, res.clone());
    return res;
  }} catch (err) {{
    const hit = await cache.match(request);
    if (hit) return hit;
    const shell = await cache.match('/phone');
    if (shell) return shell;
    return new Response('<h1>offline</h1><p>This page was never cached.</p>',
      {{ status: 503, headers: {{ 'Content-Type': 'text/html; charset=utf-8' }} }});
  }}
}}

self.addEventListener('fetch', (event) => {{
  const request = event.request;
  if (request.method !== 'GET') return;              // never cache writes
  const url = new URL(request.url);
  if (url.origin !== self.location.origin) return;   // three.js CDN etc. is not ours
  if (isApi(url)) {{
    event.respondWith(apiNetworkFirst(request));
    return;
  }}
  if (url.pathname.startsWith('/static/')) {{
    event.respondWith(staticCacheFirst(request));
    return;
  }}
  if (request.mode === 'navigate') {{
    event.respondWith(pageNetworkFirst(request));
  }}
}});
"""


# --------------------------------------------------------------------------
# the phone home screen: what it shows and what its buttons do
# --------------------------------------------------------------------------

def loop_snapshot() -> dict:
    """Every number the phone home screen puts on screen. All of them are real."""
    from . import bot_factory, ingestion, measurement, opportunity, scheduling, service

    counts = service.counts_by_state()
    verdicts = measurement.counts().get("by_verdict", {})
    bots = bot_factory.counts()
    opps = opportunity.counts()
    signals = ingestion.signal_counts()
    schedules = scheduling.list_schedules()
    state = audit.verify()
    return {
        "jobs": {
            "total": sum(counts.values()),
            "by_state": {k: v for k, v in counts.items() if v},
            "kept": counts.get("KEPT", 0),
            "killed": counts.get("KILLED", 0),
            "in_flight": sum(
                counts.get(s, 0)
                for s in ("INGESTED", "VERIFIED", "BOT_BUILT", "RUNNING", "MEASURED")
            ),
        },
        "signals": signals,
        "opportunities": opps,
        "bots": {"total": bots.get("total", 0), "by_status": bots.get("by_status", {}),
                 "verdicts": verdicts},
        "schedules": {
            "total": len(schedules),
            "enabled": sum(1 for s in schedules if s["enabled"]),
            "due": sum(1 for s in schedules if s["enabled"] and s["due"]),
            "last_tick": scheduling.last_tick(),
        },
        "audit": {
            "ok": state["ok"],
            "status": "CHAIN INTACT" if state["ok"] else "CHAIN BROKEN",
            "length": state["length"],
            "head_hash": state["head_hash"],
            "first_broken_seq": state["first_broken_seq"],
        },
        "events": audit.recent(limit=8),
    }


def buildable_opportunities(limit: int = 8) -> list[dict]:
    """VERIFIED opportunities the phone's Build bot button can act on."""
    from . import opportunity

    rows = opportunity.list_opportunities(limit=500)
    out = []
    for row in rows:
        if (row.get("verdict") or "") != "VERIFIED":
            continue
        out.append({"id": row["id"], "title": row.get("title", ""),
                    "score": row.get("composite_score"), "status": row.get("status", "")})
        if len(out) >= limit:
            break
    return out


def _record(action: str, *, ok: bool, status: str, message: str, data: dict | None = None,
            source: str = "phone") -> dict:
    return audit.record(
        COMPONENT_NAME, "phone.action", "phone", action,
        {
            "action": action,
            "label": ACTION_LABELS.get(action, action),
            "ok": ok,
            "status": status,
            "message": message,
            "initiated_from": "phone",
            "source": source,
            "device": "pwa",
            "telephony": False,
            "data": data or {},
        },
    )


def run_action(action: str, *, opportunity_id: str | None = None,
               source: str = "phone") -> dict:
    """Run one phone action through the EXISTING layer, then audit the origin.

    Nothing new is implemented here: the button calls the scheduler / ingestion /
    bot factory / voice console exactly as the desktop pages do, and the ledger
    gets one extra row saying the request came from the phone.
    """
    action = (action or "").strip().lower()
    if action not in PHONE_ACTIONS:
        message = (
            f"unknown phone action {action!r}; expected one of {', '.join(PHONE_ACTIONS)}. "
            f"There is no telephony action: no number, no SMS, no call."
        )
        # a refused action is still an action: it goes on the ledger, and says why.
        _record(action or "unknown", ok=False, status="refused", message=message, source=source)
        raise ValidationError(message)

    from . import bot_factory, ingestion, scheduling, voice

    try:
        if action == "tick":
            result = scheduling.tick()
            message = result["message"]
            data = {"fired": result["fired_count"], "due": result["due"],
                    "enabled": result["enabled"]}
        elif action == "fetch":
            result = ingestion.run_ingest(trigger="phone")
            message = result["note"]
            data = {"run_id": result["id"], "new": result["new_total"],
                    "fetched": result["fetched_total"],
                    "errors": len(result["errors"])}
        elif action == "build":
            opp_id = (opportunity_id or "").strip()
            if not opp_id:
                raise ValidationError(
                    "choose a VERIFIED opportunity first: the bot factory refuses "
                    "anything that is not VERIFIED"
                )
            result = bot_factory.build_bot(opp_id, trigger="phone")
            bot = result["bot"]
            message = (
                f"bot #{bot['id']} {bot.get('bot_name') or ''} "
                f"{'built' if result['created'] else 'already existed'}"
            ).strip()
            data = {"bot_id": bot["id"], "opportunity_id": opp_id,
                    "created": result["created"], "reused": result["reused"],
                    "deployed": False}
        else:  # speak
            result = voice.handle_command("status", source="phone")
            message = result["reply"]
            data = {"intent": result["intent"],
                    "audit_seq": result.get("audit_seq")}
    except OrchestratorError as exc:
        _record(action, ok=False, status="refused", message=str(exc), source=source)
        raise

    row = _record(action, ok=True, status="done", message=message, data=data, source=source)
    log.info("[%s] phone action %s -> %s (audit seq %s)", COMPONENT_NAME, action,
             data, row["seq"])
    return {
        "component": COMPONENT_NAME,
        "action": action,
        "label": ACTION_LABELS.get(action, action),
        "ok": True,
        "status": "done",
        "message": message,
        "data": data,
        "audit_seq": row["seq"],
        "telephony": False,
    }


def describe() -> dict:
    """What the registry / API says about this component, including what it is not."""
    return {
        "component": COMPONENT_NAME,
        "manifest": MANIFEST_URL,
        "service_worker": SW_URL,
        "cache_version": CACHE_VERSION,
        "display": DISPLAY,
        "theme_color": THEME_COLOR,
        "shell_pages": list(SHELL_PAGES),
        "api_prefixes": list(API_PREFIXES),
        "api_cached": False,
        "icons": ensure_icons()["icons"],
        "icon_engine": ensure_icons()["engine"],
        "mobile_css": MOBILE_CSS,
        "actions": [{"action": a, "label": ACTION_LABELS[a],
                     "description": ACTION_DESCRIPTIONS[a]} for a in PHONE_ACTIONS],
        "real_telephony": False,
        "phone_number": None,
        "sms": False,
        "calls": False,
        "honesty": HONESTY,
    }


class PhoneReach:
    """Tool component: the PWA shell and its one-tap actions."""

    def __call__(self, job: dict | None = None) -> dict:
        return self.handle(job or {})

    def handle(self, job: dict) -> dict:
        snapshot = loop_snapshot()
        return {
            "to_state": None,  # a tool never transitions a job
            "note": (
                f"PHONE REACH: PWA shell ({CACHE_VERSION}); loop has "
                f"{snapshot['jobs']['total']} job(s); audit chain length "
                f"{snapshot['audit']['length']}. Not telephony: no number, no SMS, no calls."
            ),
            "payload_patch": {},
            "data": {
                "cache_version": CACHE_VERSION,
                "jobs_total": snapshot["jobs"]["total"],
                "audit_length": snapshot["audit"]["length"],
                "telephony": False,
            },
        }


def register_phone_reach(registry) -> object:
    """Register the phone shell as a tool component. Idempotent."""
    from .registry import Component

    if registry.has(COMPONENT_NAME):
        return registry.get(COMPONENT_NAME)
    return registry.register(
        Component(
            name=COMPONENT_NAME,
            handles_state=None,
            handler=PhoneReach(),
            description=(
                "Phone Reach: installable PWA shell (manifest, versioned service worker, mobile "
                "CSS, generated icons) plus the one-tap phone actions (tick / fetch / build / "
                "speak), each routed through the existing layer and audited. NOT telephony: no "
                "phone number, no SMS, no calls."
            ),
            kind="tool",
        )
    )
