"""
Demo task for Live View: fake multi-page OCR that emits progress events.
Triggered via POST /live_view/demo and runs as a background thread.
"""
from __future__ import annotations

import base64
import struct
import threading
import time
import zlib
from datetime import datetime, timezone


# Minimal 8x8 grey PNG for thumbnail previews (no external files needed)
def _tiny_png_base64(r: int = 200, g: int = 200, b: int = 220) -> str:
    """Generate a tiny 8x8 solid-color PNG and return as base64."""
    width, height = 8, 8
    raw_rows = b""
    for _ in range(height):
        raw_rows += b"\x00" + bytes([r, g, b]) * width
    def _chunk(chunk_type, data):
        c = chunk_type + data
        return struct.pack(">I", len(data)) + c + struct.pack(">I", zlib.crc32(c) & 0xFFFFFFFF)
    ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
    idat = zlib.compress(raw_rows, 9)
    png = b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", idat) + _chunk(b"IEND", b"")
    return base64.b64encode(png).decode("ascii")


_DEMO_PAGES = 5

_DEMO_EXTRACTED_TEXT = [
    "AGREEMENT OF SALE\nThis Agreement is entered into as of the date last signed below...",
    "Section 2: Property Description\nLot 14, Block 3, Sunrise Estates, County of Example...",
    "Section 5: Payment Terms\nBuyer agrees to pay the sum of $425,000 in accordance with...",
    "EXHIBIT A — Legal Description\nBeginning at the Northeast corner of Section 12, T3N...",
    "SIGNATURES\n\nSeller: ___________________  Date: ___________\nBuyer: ___________________  Date: ___________",
]


def run_demo_task(event_bus, thread_id: str) -> None:
    """Run a fake multi-page OCR pipeline, emitting events to the bus.

    Designed to be called in a background thread (not async).
    """
    def emit(evt: dict):
        event_bus.emit(thread_id, evt)

    emit({"type": "status", "message": "Starting document processing…"})
    time.sleep(0.8)

    emit({
        "type": "progress",
        "message": "Converting PDF to images…",
        "progress_pct": 5,
    })
    time.sleep(1.2)

    for page in range(1, _DEMO_PAGES + 1):
        pct = int(10 + (page / _DEMO_PAGES) * 80)

        emit({
            "type": "status",
            "message": f"OCR on page {page}/{_DEMO_PAGES}…",
        })
        time.sleep(0.6)

        # Simulate thumbnail with a tinted colour per page
        tint_r = 180 + page * 10
        tint_b = 240 - page * 8
        thumb_b64 = _tiny_png_base64(tint_r, 200, tint_b)

        emit({
            "type": "preview",
            "message": f"Page {page}/{_DEMO_PAGES} scanned",
            "progress_pct": pct,
            "preview_image_base64": thumb_b64,
            "preview_text": _DEMO_EXTRACTED_TEXT[page - 1] if page <= len(_DEMO_EXTRACTED_TEXT) else "",
        })
        time.sleep(0.8)

    emit({
        "type": "progress",
        "message": "Generating final summary…",
        "progress_pct": 95,
    })
    time.sleep(1.0)

    emit({
        "type": "done",
        "message": f"Document processed — {_DEMO_PAGES} pages extracted successfully.",
        "progress_pct": 100,
    })


def start_demo_in_background(event_bus, thread_id: str) -> None:
    """Spawn a daemon thread that runs the demo task."""
    t = threading.Thread(target=run_demo_task, args=(event_bus, thread_id), daemon=True)
    t.start()
