File size: 29,871 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
"""FastAPI entrypoint for the Farient Brand Review API.

Endpoints (PRD Β§API Requirements):

* ``GET  /health``                                 β†’ liveness probe
* ``POST /api/audits``                             β†’ upload, schedule pipeline
* ``GET  /api/audits/{job_id}``                    β†’ poll status / stage
* ``GET  /api/audits/{job_id}/slides``             β†’ extended findings + image URLs
* ``GET  /api/audits/{job_id}/slides/{n}/image``   β†’ stream rendered PNG
* ``GET  /api/audits/{job_id}/export?fmt=md|json|pdf|pptx`` β†’ downloadable report

The audit identifier is named ``job_id`` everywhere on the wire, matching the
PRD ``:jobId`` URL parameter.
"""
# ruff: noqa: E402
from __future__ import annotations

import asyncio
import json
import logging
import os
import zipfile
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any

# Load apps/api/.env (gitignored) before anything reads OPENAI_API_KEY etc.
# override=False keeps real shell env winning when both are set.
from dotenv import load_dotenv as _load_dotenv
_load_dotenv(Path(__file__).parent / ".env", override=True)

from fastapi import FastAPI, File, HTTPException, Query, Request, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import (
    FileResponse,
    JSONResponse,
    PlainTextResponse,
    Response,
    StreamingResponse,
)

from schemas.api import (
    AuditCreateResponse,
    AuditExportJson,
    AuditListEntry,
    AuditListResponse,
    AuditSlidesResponse,
    AuditStatusResponse,
    FindingExtended,
    FindingMeta,
    PreflightResponse,
    SeverityCounts,
    SlideEnvelope,
    SlideEnvelopeExtended,
)
from services.event_log import read_events_since
from services.export import to_markdown
from services.export_pdf import render_audit_pdf
from services.export_pptx import annotate_pptx
from services.jobs import JobNotFoundError, JobStore
from services.orchestrator import run_audit_pipeline
from services.preflight import audit_preflight
from services.renderer import warmup as renderer_warmup

logger = logging.getLogger(__name__)

_TERMINAL_STATUSES = {"reviewed", "partial", "failed"}


# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------


def _parse_origins(raw: str) -> list[str]:
    """Split a comma-separated origin list, trimming whitespace + blanks."""
    return [origin.strip() for origin in raw.split(",") if origin.strip()]


def _max_upload_bytes() -> int:
    """Resolve the max upload size in bytes from ``MAX_UPLOAD_MB`` (default 60)."""
    raw = os.getenv("MAX_UPLOAD_MB", "60")
    try:
        mb = int(raw)
    except ValueError:
        mb = 60
    return mb * 1024 * 1024


def _jobs_root() -> Path:
    """Root directory for audit job state. ``AUDIT_JOBS_ROOT`` overrides default."""
    return Path(os.getenv("AUDIT_JOBS_ROOT", "/tmp/audits"))


def _auto_worker_enabled() -> bool:
    """Whether this process should run the in-process audit worker."""
    return os.getenv("AUDIT_AUTO_WORKER", "1").strip().lower() not in {
        "0",
        "false",
        "no",
        "off",
    }


# ---------------------------------------------------------------------------
# Application factory
# ---------------------------------------------------------------------------


def create_app() -> FastAPI:
    @asynccontextmanager
    async def lifespan(app: FastAPI):
        app.state.audit_queue = asyncio.Queue()
        app.state.audit_enqueued = set()
        app.state.audit_worker_task = None
        app.state.renderer_warmup_task = None
        # Track the in-flight audit so DELETE can cancel it mid-pipeline.
        app.state.audit_running_job_id = None
        app.state.audit_running_task = None

        if _auto_worker_enabled():
            app.state.audit_worker_task = asyncio.create_task(
                _audit_worker(app), name="audit-worker"
            )
            _recover_pending_jobs(app)

        # Pre-warm LibreOffice without blocking API readiness.
        app.state.renderer_warmup_task = asyncio.create_task(
            asyncio.to_thread(renderer_warmup), name="renderer-warmup"
        )
        yield

        for task_name in ("audit_worker_task", "renderer_warmup_task"):
            task = getattr(app.state, task_name, None)
            if task is None or task.done():
                continue
            task.cancel()
            try:
                await task
            except asyncio.CancelledError:
                pass
            except Exception:  # noqa: BLE001
                logger.exception("%s shutdown failed", task_name)

    app = FastAPI(
        title="Farient Brand Review API",
        version="0.1.0",
        lifespan=lifespan,
    )

    # `WEB_ORIGINS` (plural) is canonical; fall back to legacy `WEB_ORIGIN`.
    raw_origins = (
        os.getenv("WEB_ORIGINS")
        or os.getenv("WEB_ORIGIN")
        or "http://localhost:3000"
    )
    origins = _parse_origins(raw_origins)
    origin_regex = os.getenv("WEB_ORIGIN_REGEX") or None

    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_origin_regex=origin_regex,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # Inject a JobStore on the app state so tests can swap roots cleanly.
    app.state.job_store = JobStore(_jobs_root())

    _register_routes(app)
    return app


async def _audit_worker(app: FastAPI) -> None:
    """Single in-process queue worker.

    Serializing audit execution prevents multiple uploads from stampeding
    LibreOffice and OpenAI TPM at the same time. It is still a lightweight
    process-local worker; a deployed multi-instance setup should replace this
    with an external queue.
    """
    queue: asyncio.Queue[str] = app.state.audit_queue
    while True:
        job_id = await queue.get()
        try:
            store: JobStore = app.state.job_store
            if not store.exists(job_id):
                continue
            rec = store.read(job_id)
            if rec.status in _TERMINAL_STATUSES:
                continue
            runner_override = getattr(app.state, "agent_runner_override", None)
            # Wrap the pipeline call in a Task so DELETE can cancel it.
            pipeline_task = asyncio.create_task(
                run_audit_pipeline(job_id, store=store, runner=runner_override),
                name=f"audit-pipeline-{job_id}",
            )
            app.state.audit_running_job_id = job_id
            app.state.audit_running_task = pipeline_task
            try:
                await pipeline_task
            except asyncio.CancelledError:
                # Pipeline was cancelled (most likely by DELETE). The job dir is
                # already gone; just swallow and move on to the next queue item.
                logger.info("audit pipeline cancelled for job %s", job_id)
                continue
        except asyncio.CancelledError:
            # Worker itself is being shut down β€” propagate.
            raise
        except Exception as exc:  # noqa: BLE001
            logger.exception("audit worker failed for job %s", job_id)
            try:
                store = app.state.job_store
                if store.exists(job_id):
                    store.append_error(job_id, f"worker error: {exc}")
                    store.set_status(job_id, "failed")
            except Exception:  # noqa: BLE001
                logger.exception("failed to persist worker failure for %s", job_id)
        finally:
            app.state.audit_running_job_id = None
            app.state.audit_running_task = None
            app.state.audit_enqueued.discard(job_id)
            queue.task_done()


def _enqueue_audit(app: FastAPI, job_id: str) -> bool:
    """Queue a job once. Returns False when the in-process worker is disabled."""
    queue = getattr(app.state, "audit_queue", None)
    enqueued = getattr(app.state, "audit_enqueued", None)
    if queue is None or enqueued is None:
        return False
    if job_id in enqueued:
        return True
    enqueued.add(job_id)
    queue.put_nowait(job_id)
    return True


def _recover_pending_jobs(app: FastAPI) -> None:
    """Re-enqueue jobs left non-terminal by reloads/crashes."""
    store: JobStore = app.state.job_store
    for rec in reversed(store.list_jobs()):
        if rec.status not in _TERMINAL_STATUSES:
            _enqueue_audit(app, rec.job_id)


# ---------------------------------------------------------------------------
# Route registration
# ---------------------------------------------------------------------------


def _register_routes(app: FastAPI) -> None:  # noqa: C901 β€” single readable surface
    @app.get("/health")
    def health() -> dict[str, bool]:
        return {"ok": True}

    @app.get("/health/preflight", response_model=PreflightResponse)
    def preflight(request: Request) -> PreflightResponse:
        store: JobStore = request.app.state.job_store
        return audit_preflight(store.root)

    # ---- GET /api/audits --------------------------------------------------

    @app.get(
        "/api/audits",
        response_model=AuditListResponse,
    )
    def list_audits(request: Request) -> AuditListResponse:
        store: JobStore = request.app.state.job_store
        records = store.list_jobs()
        entries = [
            AuditListEntry(
                job_id=rec.job_id,
                file_name=rec.file_name,
                status=rec.status,
                slide_count=rec.slide_count,
                summary=rec.summary,
                created_at=rec.created_at,
                completed_at=rec.completed_at,
                errors_count=len(rec.errors),
            )
            for rec in records
        ]
        return AuditListResponse(jobs=entries)

    # ---- POST /api/audits -------------------------------------------------

    @app.post(
        "/api/audits",
        response_model=AuditCreateResponse,
        status_code=200,
    )
    async def create_audit(
        request: Request, file: UploadFile = File(...)
    ) -> AuditCreateResponse:
        store: JobStore = request.app.state.job_store
        max_bytes = _max_upload_bytes()

        # 1. Extension check.
        filename = file.filename or "deck.pptx"
        if not filename.lower().endswith(".pptx"):
            raise HTTPException(
                status_code=400,
                detail="Only .pptx files are accepted (got {!r}).".format(filename),
            )

        # 2. Content-Length pre-check (header may lie β€” streaming counter below).
        cl_header = request.headers.get("content-length")
        if cl_header:
            try:
                if int(cl_header) > max_bytes:
                    raise HTTPException(
                        status_code=413,
                        detail=(
                            f"File too large: Content-Length exceeds "
                            f"MAX_UPLOAD_MB={max_bytes // (1024 * 1024)}."
                        ),
                    )
            except ValueError:
                pass  # malformed header β€” fall through to streaming check

        # 3. Stream into a temp file in the (yet-to-be-created) job dir.
        record = store.create(file_name=filename)
        source_path = store.source_path(record.job_id)
        bytes_written = 0
        try:
            with source_path.open("wb") as out:
                while True:
                    chunk = await file.read(1024 * 1024)
                    if not chunk:
                        break
                    bytes_written += len(chunk)
                    if bytes_written > max_bytes:
                        out.close()
                        source_path.unlink(missing_ok=True)
                        store.append_error(
                            record.job_id,
                            f"Upload exceeded MAX_UPLOAD_MB={max_bytes // (1024 * 1024)}",
                        )
                        store.set_status(record.job_id, "failed")
                        raise HTTPException(
                            status_code=413,
                            detail=(
                                f"File too large: streamed bytes exceed "
                                f"MAX_UPLOAD_MB={max_bytes // (1024 * 1024)}."
                            ),
                        )
                    out.write(chunk)
        finally:
            await file.close()

        # 4. Magic-bytes check (a .pptx is a zip archive).
        if not zipfile.is_zipfile(source_path):
            source_path.unlink(missing_ok=True)
            store.append_error(
                record.job_id, "Uploaded file is not a valid PPTX (zip)."
            )
            store.set_status(record.job_id, "failed")
            raise HTTPException(
                status_code=400,
                detail="Uploaded file is not a valid PPTX (zip magic bytes missing).",
            )

        # 5. Schedule the pipeline; do NOT block the response on it. Prefer
        # the single worker queue to avoid upload bursts stampeding the LLM.
        queued = _enqueue_audit(request.app, record.job_id)
        if not queued:
            runner_override = getattr(request.app.state, "agent_runner_override", None)
            asyncio.create_task(
                run_audit_pipeline(
                    record.job_id, store=store, runner=runner_override
                )
            )

        return AuditCreateResponse(job_id=record.job_id, status="queued")

    # ---- GET /api/audits/{job_id} ----------------------------------------

    @app.get(
        "/api/audits/{job_id}",
        response_model=AuditStatusResponse,
    )
    def get_audit(request: Request, job_id: str) -> AuditStatusResponse:
        store: JobStore = request.app.state.job_store
        try:
            rec = store.read(job_id)
        except JobNotFoundError as exc:
            raise HTTPException(status_code=404, detail=str(exc)) from exc
        return rec.to_status_response()

    # ---- DELETE /api/audits/{job_id} -------------------------------------
    # Remove the entire on-disk job directory. Idempotent β€” returns 204 even
    # if the job was already gone, so the UI can do an optimistic delete and
    # not need to handle a 404 specially. Returns 404 only if the job_id has
    # never existed in this store.

    @app.delete("/api/audits/{job_id}", status_code=204)
    def delete_audit(request: Request, job_id: str) -> Response:
        store: JobStore = request.app.state.job_store
        if not store.exists(job_id):
            raise HTTPException(status_code=404, detail=f"No job at {job_id}")
        # Cancel the in-flight pipeline if this is the currently-running job.
        # Worker catches CancelledError and moves on to the next queued item.
        running_id = getattr(request.app.state, "audit_running_job_id", None)
        running_task = getattr(request.app.state, "audit_running_task", None)
        if running_id == job_id and running_task is not None and not running_task.done():
            running_task.cancel()
        # Also remove from the enqueued set so the worker skips it cleanly if
        # it gets popped before the cancel propagates (existence check in
        # _audit_worker handles the race too β€” both are belt-and-suspenders).
        enqueued = getattr(request.app.state, "audit_enqueued", None)
        if enqueued is not None:
            enqueued.discard(job_id)
        store.delete(job_id)
        return Response(status_code=204)

    # ---- GET /api/audits/{job_id}/events ---------------------------------
    # Server-Sent Events stream of status snapshots. Sends an initial event
    # immediately on connection, then re-emits whenever the on-disk JSON
    # changes. Closes when the job reaches a terminal state.

    @app.get("/api/audits/{job_id}/events")
    async def audit_events(request: Request, job_id: str) -> StreamingResponse:
        store: JobStore = request.app.state.job_store
        # Verify the job exists before opening the stream so misses still
        # return 404 rather than an empty event-stream.
        if not store.exists(job_id):
            raise HTTPException(status_code=404, detail=f"No job at {job_id}")

        async def event_generator():
            poll_interval = 0.1  # 100ms β€” invisible to client; pushes on change
            heartbeat_every = 15.0  # seconds
            last_payload: str | None = None
            last_heartbeat = asyncio.get_event_loop().time()
            # Byte offset into events.jsonl. On first read we replay the
            # whole file (offset 0) so a client connecting mid-audit catches
            # up on every slide that has already finished.
            event_offset: int = 0
            job_dir = store.job_dir(job_id)
            try:
                while True:
                    # Client disconnect detection.
                    if await request.is_disconnected():
                        break

                    try:
                        rec = store.read(job_id)
                    except JobNotFoundError:
                        # Job vanished mid-stream β€” emit an error event and stop.
                        yield "event: error\ndata: {\"detail\":\"job not found\"}\n\n"
                        return

                    # Drain new per-slide events (also runs the initial replay).
                    new_events, event_offset = read_events_since(
                        job_dir, event_offset
                    )
                    for ev in new_events:
                        ev_type = ev.get("event") or "message"
                        ev_data = ev.get("data", {})
                        try:
                            data_str = json.dumps(ev_data, ensure_ascii=False)
                        except (TypeError, ValueError):
                            continue
                        # SSE: event-name lines must precede the data line.
                        yield f"event: {ev_type}\ndata: {data_str}\n\n"

                    payload = rec.to_status_response().model_dump_json()
                    if payload != last_payload:
                        yield f"data: {payload}\n\n"
                        last_payload = payload

                    # Heartbeat to keep proxies / browsers from killing the
                    # connection during long idle stretches.
                    now = asyncio.get_event_loop().time()
                    if now - last_heartbeat >= heartbeat_every:
                        yield ": keepalive\n\n"
                        last_heartbeat = now

                    # If terminal, drain any final events one more time then
                    # send the 'done' event and close.
                    if rec.status in {"reviewed", "partial", "failed"}:
                        new_events, event_offset = read_events_since(
                            job_dir, event_offset
                        )
                        for ev in new_events:
                            ev_type = ev.get("event") or "message"
                            ev_data = ev.get("data", {})
                            try:
                                data_str = json.dumps(ev_data, ensure_ascii=False)
                            except (TypeError, ValueError):
                                continue
                            yield f"event: {ev_type}\ndata: {data_str}\n\n"
                        yield f"event: done\ndata: {payload}\n\n"
                        return

                    await asyncio.sleep(poll_interval)
            except asyncio.CancelledError:
                # Connection cancelled β€” propagate cleanly.
                raise
            except Exception:  # noqa: BLE001
                logger.exception("SSE generator failed for job %s", job_id)
                # Best-effort error event; if the connection is broken it
                # will just be dropped.
                try:
                    yield "event: error\ndata: {\"detail\":\"stream error\"}\n\n"
                except Exception:  # noqa: BLE001
                    pass

        headers = {
            "Cache-Control": "no-cache, no-transform",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no",
        }
        return StreamingResponse(
            event_generator(),
            media_type="text/event-stream",
            headers=headers,
        )

    # ---- GET /api/audits/{job_id}/slides ---------------------------------

    @app.get(
        "/api/audits/{job_id}/slides",
        response_model=AuditSlidesResponse,
    )
    def get_audit_slides(
        request: Request, job_id: str
    ) -> AuditSlidesResponse:
        store: JobStore = request.app.state.job_store
        try:
            rec = store.read(job_id)
        except JobNotFoundError as exc:
            raise HTTPException(status_code=404, detail=str(exc)) from exc

        export = _read_export_or_empty(store, job_id, rec.file_name, rec.slide_count)

        # Convert strict slides β†’ extended slides; tag a default finding_meta
        # for any finding that came in without one (the runner already tags
        # source/must_flag β€” but the strict export wipes that, so we re-hydrate
        # from the raw findings.json).
        extended_slides: list[SlideEnvelopeExtended] = []
        raw_extended = _read_extended_slides(store, job_id)
        for env in export.slides:
            ext_findings: list[FindingExtended] = []
            raw_for_slide = raw_extended.get(env.slide_number, [])
            for idx, f in enumerate(env.findings):
                meta = (
                    raw_for_slide[idx]
                    if idx < len(raw_for_slide)
                    else FindingMeta(source="merged", must_flag=False)
                )
                ext_findings.append(
                    FindingExtended(**f.model_dump(), finding_meta=meta)
                )
            extended_slides.append(
                SlideEnvelopeExtended(
                    slide_number=env.slide_number,
                    image_url=_image_url_if_rendered(store, job_id, env.slide_number),
                    findings=ext_findings,
                )
            )

        return AuditSlidesResponse(
            job_id=job_id,
            file_name=rec.file_name,
            slide_count=export.slide_count,
            summary=export.summary,
            slides=extended_slides,
        )

    # ---- GET /api/audits/{job_id}/slides/{n}/image -----------------------

    @app.get("/api/audits/{job_id}/slides/{n}/image")
    def get_slide_image(
        request: Request, job_id: str, n: int
    ) -> FileResponse:
        store: JobStore = request.app.state.job_store
        if not store.exists(job_id):
            raise HTTPException(status_code=404, detail="job not found")
        path = store.slide_image_path(job_id, n)
        if not path.exists():
            raise HTTPException(
                status_code=404, detail=f"slide {n} not rendered"
            )
        return FileResponse(
            path,
            media_type="image/png",
            headers={"Cache-Control": "public, max-age=86400"},
        )

    # ---- GET /api/audits/{job_id}/export?fmt=md|json|pdf|pptx ------------

    @app.get("/api/audits/{job_id}/export")
    def get_audit_export(
        request: Request,
        job_id: str,
        fmt: str = Query(default="json", pattern="^(md|json|pdf|pptx)$"),
    ) -> Response:
        store: JobStore = request.app.state.job_store
        try:
            rec = store.read(job_id)
        except JobNotFoundError as exc:
            raise HTTPException(status_code=404, detail=str(exc)) from exc

        export = _read_export_or_empty(store, job_id, rec.file_name, rec.slide_count)

        base = Path(rec.file_name).stem or "audit"
        if fmt == "json":
            payload = export.model_dump()
            return JSONResponse(
                content=payload,
                headers={
                    "Content-Disposition": (
                        f'attachment; filename="{base}-audit-{job_id}.json"'
                    )
                },
            )
        if fmt == "pdf":
            try:
                pdf_bytes = render_audit_pdf(export)
            except Exception as exc:  # noqa: BLE001
                logger.exception("pdf export failed for job %s", job_id)
                raise HTTPException(
                    status_code=500,
                    detail=f"PDF render failed: {exc}",
                ) from exc
            return Response(
                content=pdf_bytes,
                media_type="application/pdf",
                headers={
                    "Content-Disposition": (
                        f'attachment; filename="{base}-audit-{job_id}.pdf"'
                    )
                },
            )
        if fmt == "pptx":
            source = store.source_path(job_id)
            if not source.exists():
                # Old jobs (pre-source-preservation) cannot be annotated.
                raise HTTPException(
                    status_code=501,
                    detail=(
                        "Annotated PPTX export is unavailable for this audit: "
                        "the original deck was not preserved on the server. "
                        "Re-upload the deck to enable annotated export."
                    ),
                )
            try:
                pptx_bytes = annotate_pptx(source, export)
            except FileNotFoundError as exc:
                raise HTTPException(
                    status_code=501,
                    detail=str(exc),
                ) from exc
            except Exception as exc:  # noqa: BLE001
                logger.exception("pptx export failed for job %s", job_id)
                raise HTTPException(
                    status_code=500,
                    detail=f"PPTX annotation failed: {exc}",
                ) from exc
            # Build a safe filename derived from the original deck name.
            original = Path(rec.file_name).name or f"deck-{job_id}.pptx"
            if not original.lower().endswith(".pptx"):
                original = f"{original}.pptx"
            out_name = f"annotated-{original}"
            return Response(
                content=pptx_bytes,
                media_type=(
                    "application/vnd.openxmlformats-"
                    "officedocument.presentationml.presentation"
                ),
                headers={
                    "Content-Disposition": (
                        f'attachment; filename="{out_name}"'
                    )
                },
            )
        # fmt == "md"
        body = to_markdown(export)
        return PlainTextResponse(
            content=body,
            media_type="text/markdown",
            headers={
                "Content-Disposition": (
                    f'attachment; filename="{base}-audit-{job_id}.md"'
                )
            },
        )


# ---------------------------------------------------------------------------
# Internal helpers (used by routes)
# ---------------------------------------------------------------------------


def _read_export_or_empty(
    store: JobStore, job_id: str, file_name: str, slide_count: int
) -> AuditExportJson:
    """Read findings.json into ``AuditExportJson``; empty result if not yet written."""
    path = store.findings_path(job_id)
    if not path.exists():
        return AuditExportJson(
            job_id=job_id,
            file_name=file_name,
            slide_count=slide_count,
            summary=SeverityCounts(),
            slides=[
                SlideEnvelope(slide_number=n, findings=[])
                for n in range(1, slide_count + 1)
            ],
        )
    try:
        data: Any = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return AuditExportJson(
            job_id=job_id,
            file_name=file_name,
            slide_count=slide_count,
            summary=SeverityCounts(),
            slides=[],
        )
    return AuditExportJson.model_validate(data)


def _read_extended_slides(
    store: JobStore, job_id: str
) -> dict[int, list[FindingMeta]]:
    """Load per-slide finding_meta lists from a sidecar file (if present).

    Currently the orchestrator only persists the strict shape β€” the
    ``/slides`` endpoint synthesises a default ``FindingMeta(source='merged',
    must_flag=False)`` per finding. This helper exists so a future
    enhancement can persist the extended shape without changing the route.
    """
    sidecar = store.job_dir(job_id) / "findings_extended.json"
    if not sidecar.exists():
        return {}
    try:
        data = json.loads(sidecar.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return {}
    out: dict[int, list[FindingMeta]] = {}
    for slide in data.get("slides", []):
        n = int(slide["slide_number"])
        metas: list[FindingMeta] = []
        for f in slide.get("findings", []):
            meta = f.get("finding_meta")
            if meta is None:
                continue
            metas.append(FindingMeta.model_validate(meta))
        out[n] = metas
    return out


def _image_url_if_rendered(
    store: JobStore, job_id: str, slide_number: int
) -> str | None:
    if store.slide_image_path(job_id, slide_number).exists():
        return f"/api/audits/{job_id}/slides/{slide_number}/image"
    return None


# ---------------------------------------------------------------------------
# Module-level app instance (uvicorn entrypoint)
# ---------------------------------------------------------------------------


app = create_app()