"""Drone camera ground-camera demo. Data and authority arrive only through the Horizon app host."""

import marimo

__generated_with = "0.23.14"
app = marimo.App(width="full")


@app.cell
def _():
    import marimo as mo
    from scrydon import apps

    return apps, mo


@app.cell
def _(apps):
    # `pictures` is unfiltered: every pushed frame, including a heartbeat or a
    # plain --snapshot-every still with no detection. A query's rows arrive in
    # source order, not time order, and a query with more rows than its
    # max_objects is refused as a whole -- so it is not "the latest one" but a
    # bounded set the "Latest picture" panel picks the newest frame from. Past
    # 500 frames in the table (about 17 minutes of phone frames at one every
    # 2 s) the query, and so the panel, is unavailable.
    # Comments stay outside the call, so any host's compiler reads it.
    access = apps.declare(
        ontologies=[apps.ontology("scrydon-pack-drone-camera-v1", alias="drone")],
        queries=[
            apps.query(
                "detections", ontology="drone", object_type="ImageDetection",
                properties=[
                    "detectionId", "frame", "detectionClass", "confidence",
                    "boxX", "boxY", "boxW", "boxH", "capturedAt", "sensorEntityId",
                    "declaredLat", "declaredLon", "declaredBearingDeg", "positionQuality",
                ],
                filter=[{"property": "detectionClass", "op": "eq", "value": "drone"}],
                max_objects=500, live=True, stale_after_ms=60_000,
            ),
            apps.query(
                "pictures", ontology="drone", object_type="ImageDetection",
                properties=[
                    "detectionId", "frame", "capturedAt", "sensorEntityId",
                    "declaredLat", "declaredLon", "declaredBearingDeg", "positionQuality",
                ],
                max_objects=500, live=True, required=False, stale_after_ms=60_000,
            ),
            apps.query(
                "clips", ontology="drone", object_type="DroneClip",
                properties=["clipId", "detectionId", "clip", "capturedAt", "sensorEntityId"],
                max_objects=100, live=True, required=False, stale_after_ms=60_000,
            ),
            apps.query(
                "watch_detections", ontology="drone", object_type="DroneInViewDetection",
                properties=[
                    "detectionId", "watchSlug", "kind", "severity", "areaId", "entityId",
                    "firedAt", "acknowledgementStatus", "acknowledgedBy", "acknowledgedAt",
                ],
                max_objects=500, live=True, required=False, stale_after_ms=60_000,
            ),
        ],
        links=[apps.link(
            "detection-clip", ontology="drone", link_type="DroneClipOfDetection",
            source_query="detections", target_query="clips", max_objects=1,
            required=False,
        )],
        actions=[apps.allow_action(
            "acknowledge-drone-camera-detection", ontology="drone",
            action_type="acknowledge-drone-camera-detection",
            input_properties=["detectionId"], required=False,
        )],
        watches=[
            apps.allow_watch("drone-in-view", ontology="drone", watch="drone-in-view", required=False),
        ],
    )
    return access


@app.cell
def _(apps):
    # Indoors there is no GPS fix: every detection carries the
    # same declared camera position. `positionQuality` draws the dashed,
    # "declared position" marker style instead of a measured-GPS fix, and
    # `declaredBearingDeg` (when set) turns the marker to the camera's facing.
    camera = apps.points(
        "detections", latitude="declaredLat", longitude="declaredLon",
        label="detectionClass", classification="detectionClass",
        heading="declaredBearingDeg", position_quality="positionQuality",
        selection_group="detections", title="Camera (declared position)",
    )
    picture = apps.map(
        "detections", latitude="declaredLat", longitude="declaredLon",
        observed_at="capturedAt", received_at="capturedAt",
        label="detectionClass", point_layers=[camera],
        center=(2.3522, 48.8566), zoom=16, selection_group="map-detections",
        title="Room picture",
    )
    return (picture,)


@app.cell
def _(apps):
    detections = apps.table(
        "detections", columns={
            "detectionClass": "Class", "confidence": "Confidence",
            "capturedAt": "Captured at",
        },
        selection_group="detections", title="Drone detections",
    )
    # `media=["frame"]` renders the frame as an image from the governed read
    # route, with its box drawn from the stored region -- never a bearer URL.
    details = apps.details(
        "detections", fields={
            "frame": "Frame", "detectionClass": "Class", "confidence": "Confidence",
            "boxX": "Box left", "boxY": "Box top", "boxW": "Box width", "boxH": "Box height",
            "capturedAt": "Captured at", "sensorEntityId": "Sensor",
            "declaredLat": "Declared latitude", "declaredLon": "Declared longitude",
            "declaredBearingDeg": "Declared bearing", "positionQuality": "Position quality",
        },
        media=["frame"], selection_group="detections", title="Selected detection",
    )
    # The clip recorded around the selected detection, if any. `media=["clip"]`
    # renders it as `<video>` once the UI supports a video media item; until
    # the video-clip server support lands, it falls back to a placeholder.
    clip = apps.related(
        "detection-clip", columns={"clipId": "Clip", "capturedAt": "Recorded at"},
        source_selection_group="detections", selection_group="clip",
        title="Clip",
    )
    clip_player = apps.details(
        "clips", fields={"clip": "Clip", "capturedAt": "Recorded at"},
        media=["clip"], selection_group="clip", title="Clip player",
    )
    return clip, clip_player, details, detections


@app.cell
def _(apps):
    # The most recently pushed frame, detection or not -- a steady picture
    # stream from --snapshot-every and the heartbeat, not only drone sightings.
    # `newest_by` picks it in the browser by capture time; nothing selects it.
    latest_picture = apps.details(
        "pictures", fields={
            "frame": "Frame", "capturedAt": "Captured at", "sensorEntityId": "Sensor",
        },
        media=["frame"], newest_by="capturedAt", selection_group="pictures",
        title="Latest picture",
    )
    return (latest_picture,)


@app.cell
def _(apps):
    alerts = apps.alerts(
        "watch_detections", columns={
            "watchSlug": "Rule", "severity": "Severity", "firedAt": "Detected",
            "acknowledgementStatus": "Acknowledgement",
        },
        severity="severity", status="acknowledgementStatus",
        acknowledge_action="acknowledge-drone-camera-detection", acknowledge_input="detectionId",
        selection_group="alerts",
        title="Drone-in-view alerts",
    )
    alert_details = apps.details(
        "watch_detections", fields={
            "watchSlug": "Rule", "kind": "Event class", "areaId": "Area",
            "entityId": "Detection", "firedAt": "Detected",
            "acknowledgedBy": "Acknowledged by", "acknowledgedAt": "Acknowledged at",
        }, selection_group="alerts", title="Selected alert",
    )
    return alert_details, alerts


@app.cell
def _(
    alert_details, alerts, clip, clip_player, details, detections,
    latest_picture, mo, picture,
):
    # The picture takes the viewer's full height; the rail beside it is a tab
    # per worklist, each with the inspector its selection drives.
    mo.hstack(
        [
            picture,
            mo.ui.tabs({
                "Drone detections": mo.vstack(
                    [detections, details, clip, clip_player], gap=0.75,
                ),
                "Latest picture": mo.vstack([latest_picture], gap=0.75),
                "Alerts": mo.vstack([alerts, alert_details], gap=0.75),
            }),
        ],
        widths=[2, 1], gap=1, align="start",
    )
    return


if __name__ == "__main__":
    app.run()
