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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
"""FastAPI backend for AI Tester Platform."""

import json
import mimetypes
import os
import sys
import warnings
from contextlib import asynccontextmanager
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse

# NOTE: ``urllib.request.Request`` must be imported under an alias to avoid
# clashing with ``fastapi.Request`` (see ``_load_desktop_release_feed``).
from urllib.request import Request as UrlRequest, urlopen

from dotenv import load_dotenv
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

# Suppress noisy third-party warnings that do not affect runtime behavior.
try:
    from urllib3.exceptions import NotOpenSSLWarning

    warnings.filterwarnings("ignore", category=NotOpenSSLWarning)
except Exception:
    pass

warnings.filterwarnings(
    "ignore",
    message=r".*PydanticDeprecatedSince.*",
    category=DeprecationWarning,
    module=r"pyiceberg\..*",
)
warnings.filterwarnings(
    "ignore",
    message=r".*enablePackrat.*|.*escChar.*|.*unquoteResults.*",
    category=DeprecationWarning,
    module=r"pyiceberg\..*",
)

# Ensure browsers render `.webp` screenshots served from `/output`.
mimetypes.add_type("image/webp", ".webp")

# Load env vars from project root
env_path = Path(__file__).parent.parent.parent / ".env"
load_dotenv(dotenv_path=env_path)

# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from src.api.routes import (
    admin_llm_keys,
    admin_settings,
    ai_proxy,
    bots,
    bug_tickets,
    evaluations,
    integrations as integrations_routes,
    knowledge_sources,
    openproject as openproject_routes,
    personas,
    report_records,
    reports,
    scenarios,
    sessions,
    workspaces,
)
from src.api.routes import (
    auth as auth_routes,
)
from src.db import init_db
from src.utils.env import env_bool, env_int, env_str
from src.utils.logging import configure_logging, get_logger
from src.web.reports_dashboard import router as reports_dashboard_router

# Configure logging once, before any module starts emitting records.
configure_logging()
logger = get_logger(__name__)


def _is_production() -> bool:
    """Production mode is opt-in via ``ENV=production`` (canonical) or
    ``DEBUG=false`` paired with a non-empty ``DATABASE_URL`` pointing to
    Postgres. Default is dev-friendly (returns False)."""
    env = env_str("ENV", "").strip().lower()
    if env in {"production", "prod"}:
        return True
    if env in {"development", "dev", "local", "test", "staging"}:
        return False
    # Fallback: assume prod only if explicitly using Postgres + DEBUG=false.
    db_url = env_str("DATABASE_URL", "")
    return ("postgresql" in db_url or "postgres://" in db_url) and not env_bool("DEBUG", False)


def _validate_production_env() -> None:
    """Fail-fast on missing critical env vars in production."""
    missing: list[str] = []
    if not env_str("DATABASE_URL", "").strip():
        missing.append("DATABASE_URL")
    # Encryption key for stored LLM keys — required when admin LLM keys are used.
    if not env_str("APP_SECRETS_MASTER_KEY", "").strip():
        missing.append("APP_SECRETS_MASTER_KEY")
    # If auth is enforced, we need at least Supabase URL + anon key configured.
    if env_bool("ENFORCE_AUTH", False):
        for var in ("SUPABASE_URL", "SUPABASE_ANON_KEY"):
            if not env_str(var, "").strip():
                missing.append(var)
    if missing:
        raise RuntimeError(
            "Production startup aborted — missing required env vars: " + ", ".join(missing)
        )


def _parse_allowed_origins() -> list[str]:
    """Read ALLOWED_ORIGINS as comma-separated list. Empty in prod by default."""
    raw = env_str("ALLOWED_ORIGINS", "")
    parts = [p.strip() for p in raw.split(",") if p.strip()]
    if parts:
        return parts
    # Permissive default only in non-production dev.
    if not _is_production():
        return ["*"]
    return []


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Lifespan context manager for startup/shutdown events."""
    # Validate environment first so the app refuses to come up half-broken.
    if _is_production():
        _validate_production_env()
        logger.info("startup: production env validated")

    init_db()
    try:
        from src.core.knowledge_memory import knowledge_memory_service

        recovered = knowledge_memory_service.recover_orphan_runs()
        if recovered:
            logger.info(
                "startup: knowledge-memory recovered orphan crawl runs",
                extra={"recovered": recovered},
            )
    except Exception:
        logger.exception("startup: knowledge-memory recovery failed")
    try:
        # Test sessions left RUNNING in DB by a previous process die when
        # the process dies (daemon thread). Without this, those rows stay
        # in `running` forever. session_runner.recover_orphan_sessions()
        # finalizes them as FAILED with `error_message=process_restart_*`
        # so the UI shows them as interrotte invece di pendenti.
        from src.api.session_runner import session_runner

        recovered_sessions = session_runner.recover_orphan_sessions()
        if recovered_sessions:
            logger.info(
                "startup: test-session recovery finalized orphan sessions",
                extra={"recovered": recovered_sessions},
            )
    except Exception:
        logger.exception("startup: test-session recovery failed (non-fatal)")

    # Stesso problema dei test session orphans, applicato al post-session AIS
    # judge: il BackgroundTask di `_run_session_judge_sync` muore quando il
    # container HF si riavvia (deploy / OOM / scaling). Il record DB resta
    # `judge_status='running'` per sempre. Qui finalizziamo tutto come
    # `failed` con un messaggio chiaro, così l'utente può rilanciare via
    # "Rivaluta tutti" invece di aspettare un job morto.
    try:
        from datetime import datetime, timedelta

        from src.db import get_db as _get_db
        from src.db.models import TestSessionModel

        db = _get_db()
        # 1800s = 30min default — copre rebuild lenti del container HF e
        # sessioni con molti turni (judge GPT-4.5 ~15-30s/turn × 60 turn).
        stale_after_seconds = int(os.getenv("JUDGE_STALE_AFTER_SECONDS", "1800"))
        now = datetime.utcnow()
        cutoff = now - timedelta(seconds=stale_after_seconds)
        with db.get_session() as s:
            stale = (
                s.query(TestSessionModel)
                .filter(TestSessionModel.judge_status.in_(["running", "pending"]))
                .all()
            )
            recovered_judge = 0
            for row in stale:
                started_at = row.judge_started_at
                # Check heartbeat: se il judge_progress ha last_heartbeat_at
                # recente (< stale_after_seconds), il job era vivo poco fa →
                # presumibilmente è morto col restart MA può ripartire
                # rapidamente se il restart è stato breve. Decisione: comunque
                # marchiamo failed perché il BG task non sopravvive comunque
                # al restart; se l'admin clicca "Rivaluta tutti" riparte.
                # Manteniamo il running solo se started_at è recentissimo
                # (< stale_after_seconds): caso edge in cui l'app si è appena
                # avviata mentre un altro worker stava già scrivendo.
                if started_at is not None and started_at > cutoff:
                    continue  # job fresco — lascia stare
                row.judge_status = "failed"
                row.judge_completed_at = now
                age_str = ""
                if started_at is not None:
                    age_min = int((now - started_at).total_seconds() / 60)
                    age_str = f" Job started {age_min} min ago."
                prev_err = (row.judge_error or "")[:200]
                row.judge_error = (
                    "Stale: worker terminated before completion (likely container "
                    "restart o crash)." + age_str + " Reset automatico all'avvio. "
                    "Clicca 'Rivaluta tutti' per ripartire."
                    + (f" Previous error: {prev_err}" if prev_err else "")
                )
                recovered_judge += 1
            if recovered_judge:
                s.commit()
                logger.info(
                    "startup: judge recovery finalized stale runs",
                    extra={"recovered": recovered_judge, "cutoff_sec": stale_after_seconds},
                )
    except Exception:
        logger.exception("startup: judge stale recovery failed (non-fatal)")

    # OpenProject retry loop (best-effort: never blocks startup).
    openproject_retry_task = None
    try:
        import asyncio as _asyncio
        from src.integrations.openproject.config import OpenProjectConfig
        from src.integrations.openproject.retry_loop import run_retry_loop

        _op_cfg = OpenProjectConfig.from_env()
        if _op_cfg is not None and _op_cfg.retry_loop_enabled:
            openproject_retry_task = _asyncio.create_task(run_retry_loop())
            logger.info("startup: openproject retry loop scheduled")
    except Exception:
        logger.exception("startup: openproject retry loop bootstrap failed")

    # Screenshot purge loop (best-effort): ogni 24h scansiona le sessioni più
    # vecchie di SCREENSHOT_RETENTION_DAYS (default 45) e cancella i file
    # `.webp` dal bucket Supabase Storage + ripulisce i riferimenti nel DB.
    # Non blocca lo startup; in caso di errori in singoli batch continua.
    # Disabilita via SCREENSHOT_PURGE_ENABLED=false se serve troubleshooting.
    purge_task = None
    try:
        import asyncio as _asyncio

        if env_bool("SCREENSHOT_PURGE_ENABLED", True):
            retention_days = env_int("SCREENSHOT_RETENTION_DAYS", 45)
            interval_seconds = env_int("SCREENSHOT_PURGE_INTERVAL_SECONDS", 86400)

            async def _purge_loop() -> None:
                # Aspetta 5min al boot per non concorrere con altre init.
                await _asyncio.sleep(300)
                while True:
                    try:
                        from src.db import get_db as _get_db
                        from src.db.repositories import SessionRepository

                        _db = _get_db()
                        with _db.get_session() as _s:
                            repo = SessionRepository(_s)
                            stats = repo.purge_old_screenshots(
                                older_than_days=retention_days
                            )
                            _s.commit()
                        if stats.get("sessions_processed"):
                            logger.info(
                                "purge: screenshot retention sweep completed",
                                extra=stats,
                            )
                    except Exception:
                        logger.exception(
                            "purge: screenshot retention sweep failed (non-fatal)"
                        )
                    await _asyncio.sleep(interval_seconds)

            purge_task = _asyncio.create_task(_purge_loop())
            logger.info(
                "startup: screenshot purge loop scheduled "
                f"(retention={retention_days}d, interval={interval_seconds}s)"
            )
    except Exception:
        logger.exception("startup: screenshot purge loop bootstrap failed")

    yield

    # Shutdown — swallow CancelledError too (it's a BaseException in 3.9+,
    # so a bare `except Exception` lets it bubble up and breaks shutdown).
    if openproject_retry_task is not None:
        openproject_retry_task.cancel()
        try:
            await openproject_retry_task
        except BaseException:
            pass
    if purge_task is not None:
        purge_task.cancel()
        try:
            await purge_task
        except BaseException:
            pass


_PRODUCTION = _is_production()

app = FastAPI(
    title="AI Tester Platform API",
    description="API for testing conversational AI chatbots",
    version="1.0.0",
    lifespan=lifespan,
    # Disable interactive docs in production to avoid leaking the schema.
    docs_url=None if _PRODUCTION else "/docs",
    redoc_url=None if _PRODUCTION else "/redoc",
    openapi_url=None if _PRODUCTION else "/openapi.json",
)


# ---- Middleware (order matters: GZip after CORS so CORS headers gzip too) ----
_allowed_origins = _parse_allowed_origins()
app.add_middleware(
    CORSMiddleware,
    allow_origins=_allowed_origins,
    allow_origin_regex=env_str("ALLOWED_ORIGIN_REGEX", "") or None,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allow_headers=["*"],
    expose_headers=["X-Request-ID"],
)
app.add_middleware(GZipMiddleware, minimum_size=1024)
logger.info(
    "cors: configured",
    extra={"allowed_origins": _allowed_origins, "production": _PRODUCTION},
)


# RBAC: viewer-mutation guard middleware
# ----------------------------------------------------------------------------
# Il ruolo `viewer` è read-only (vedi src/api/auth.py). Per evitare di
# annotare 80+ endpoint con `Depends(require_not_viewer)`, lo blocco a
# livello middleware su tutti i metodi mutanti di /api/* — esclusi gli
# endpoint di auth (signin/signout/me) che devono restare accessibili.
#
# Costo per request mutante: 1 chiamata a `get_current_user` (cache della
# decodifica JWT). I metodi safe (GET/HEAD/OPTIONS) bypassano subito.
@app.middleware("http")
async def viewer_mutation_guard(request: Request, call_next):
    from src.utils.env import env_bool as _env_bool_mw
    if not _env_bool_mw("ENFORCE_AUTH", False):
        return await call_next(request)
    method = request.method.upper()
    if method not in {"POST", "PUT", "DELETE", "PATCH"}:
        return await call_next(request)
    path = request.url.path
    if not path.startswith("/api/"):
        return await call_next(request)
    # Whitelist endpoint auth: signin/signout/me devono restare invocabili
    # da chiunque (anche viewer fa logout, refresh, ecc.).
    if path.startswith("/api/auth/signin") \
       or path.startswith("/api/auth/signout") \
       or path == "/api/auth/me" \
       or path.startswith("/api/auth/refresh"):
        return await call_next(request)
    # Decodifica auth header senza rompere se assente: l'auth dep
    # dell'endpoint farà comunque 401 a valle.
    auth_header = request.headers.get("authorization", "")
    if not auth_header.lower().startswith("bearer "):
        return await call_next(request)
    bearer = auth_header[7:].strip()
    if not bearer:
        return await call_next(request)
    try:
        from fastapi.security import HTTPAuthorizationCredentials
        from src.api.auth import get_current_user
        credentials = HTTPAuthorizationCredentials(scheme="Bearer", credentials=bearer)
        user = await get_current_user(credentials)
    except Exception:
        # Token invalido / Supabase down: lascia che la dep dell'endpoint
        # decida (probabilmente 401). Non bloccare qui.
        return await call_next(request)
    if user.is_viewer:
        return JSONResponse(
            status_code=403,
            content={"detail": "Viewer role: action not allowed (read-only access)"},
        )
    # Cache user su request.state così le dep `require_auth_if_enabled`
    # downstream lo riusano (no doppio fetch Supabase).
    request.state.user = user
    return await call_next(request)


# Global exception handlers
@app.exception_handler(ValueError)
async def value_error_handler(request: Request, exc: ValueError):
    # ValueError messages are usually safe (validation/parse errors) but we
    # still avoid leaking the raw repr in production.
    detail = str(exc) if not _PRODUCTION else "Invalid input"
    logger.warning("value_error", extra={"path": request.url.path, "error": str(exc)})
    return JSONResponse(status_code=422, content={"detail": detail})


@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
    logger.exception("unhandled_exception", extra={"path": request.url.path})
    return JSONResponse(status_code=500, content={"detail": "Internal server error"})


# Include API routes
app.include_router(auth_routes.router, prefix="/api/auth", tags=["auth"])
app.include_router(bots.router, prefix="/api/bots", tags=["bots"])
app.include_router(personas.router, prefix="/api/personas", tags=["personas"])
app.include_router(scenarios.router, prefix="/api/scenarios", tags=["scenarios"])
app.include_router(sessions.router, prefix="/api/sessions", tags=["sessions"])
app.include_router(sessions.ws_router, prefix="/api/sessions", tags=["sessions"])
app.include_router(reports.router, prefix="/api/reports", tags=["reports"])
app.include_router(ai_proxy.router, prefix="/api/ai", tags=["ai"])
app.include_router(workspaces.router, prefix="/api/workspaces", tags=["workspaces"])
app.include_router(admin_llm_keys.router, prefix="/api/admin/llm", tags=["admin-llm"])
app.include_router(admin_settings.router, prefix="/api/admin", tags=["admin-settings"])
app.include_router(
    knowledge_sources.router, prefix="/api/knowledge-sources", tags=["knowledge-sources"]
)
app.include_router(evaluations.router, prefix="/api/evaluations", tags=["evaluations"])
app.include_router(bug_tickets.router, prefix="/api/bug-tickets", tags=["bug-tickets"])
app.include_router(
    openproject_routes.router, prefix="/api/openproject", tags=["openproject"]
)
app.include_router(
    integrations_routes.router, prefix="/api/integrations", tags=["integrations"]
)
app.include_router(report_records.router, prefix="/api/report-records", tags=["report-records"])
app.include_router(reports_dashboard_router)

# Static files — wrapped to set a sensible Cache-Control header. We use
# ``no-cache`` rather than a long TTL because the bundle filenames are stable
# (no content-hash) and the platform pushes CSS/JS updates often: long TTLs
# would strand users on stale assets after a deploy. ``no-cache`` still
# benefits from ETag/If-None-Match revalidation.
class _CachedStaticFiles(StaticFiles):
    def __init__(self, *args, cache_control: str = "no-cache", **kwargs):
        super().__init__(*args, **kwargs)
        self._cache_control = cache_control

    async def get_response(self, path, scope):
        response = await super().get_response(path, scope)
        # 4 tier di caching:
        #  1) vendor/* (Chart.min, Alpine.min, ecc.) — bundle frozen,
        #     cache lunghissima + immutable.
        #  2) URL con cache-buster `?v=<asset_v>` (es. app.js?v=abc123) — il
        #     fingerprint viene rigenerato ad ogni deploy via `_compute_asset_version`
        #     dei file critici, quindi possiamo cachare aggressivamente
        #     immutable. Risparmia 10-15 round-trip 304 per page nav.
        #  3) Asset binari (img, font, ico) — content immutabile di natura,
        #     cache lunga ma senza `immutable` (può cambiare al refresh del brand).
        #  4) JS/CSS principali serviti SENZA query string (es. bookmark/legacy)
        #     — fallback no-cache così l'utente è sempre freschissimo.
        path_lower = path.lower()
        has_version_buster = b"v=" in (scope.get("query_string", b"") or b"")
        if path.startswith("vendor/"):
            response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
        elif has_version_buster and path_lower.endswith((".js", ".css", ".mjs")):
            # URL con fingerprint => content è "immutabile" per definizione
            # (deploy successivo => fingerprint diverso => URL nuovo).
            response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
        elif path_lower.endswith((
            ".png", ".jpg", ".jpeg", ".svg", ".ico", ".gif", ".webp",
            ".woff", ".woff2", ".ttf", ".otf", ".eot",
        )):
            response.headers["Cache-Control"] = "public, max-age=2592000"
        else:
            response.headers["Cache-Control"] = self._cache_control
        return response


def _compute_asset_version(static_dir: Path) -> str:
    """Fingerprint SHA1 (10 char) dei file static critici per cache-busting.

    Combina app.css + ui-busy.css + tutti i js/ui/*.js + app.js. Cambia ad
    ogni modifica del bundle → invalida cache browser solo quando serve.
    Tollerante a file mancanti (best-effort).
    """
    import hashlib
    targets = [
        # Bundle globali (caricati in base.html su ogni pagina)
        static_dir / "app.css",
        static_dir / "css" / "ui-busy.css",
        static_dir / "js" / "ui" / "theme.js",
        static_dir / "js" / "ui" / "focus-trap.js",
        static_dir / "js" / "ui" / "toast.js",
        static_dir / "js" / "ui" / "dialog.js",
        static_dir / "js" / "ui" / "dropdown.js",
        static_dir / "js" / "ui" / "tabs.js",
        static_dir / "js" / "ui" / "ais-grade.js",
        static_dir / "js" / "app.js",
        # Per-page bundle (estratti dagli inline <script>/<style>). Aggiungili
        # qui quando estrai inline JS da altre pagine così il fingerprint
        # cambia anche se modifichi solo questi.
        static_dir / "css" / "pages" / "sessions.css",
        static_dir / "js" / "pages" / "sessions.js",
        static_dir / "css" / "pages" / "admin-settings.css",
        static_dir / "js" / "pages" / "admin-settings.js",
        static_dir / "js" / "pages" / "admin-users.js",
        static_dir / "css" / "pages" / "reports.css",
        static_dir / "js" / "pages" / "reports.js",
    ]
    h = hashlib.sha1()
    for f in targets:
        try:
            h.update(f.read_bytes())
        except (FileNotFoundError, OSError):
            continue
    return h.hexdigest()[:10]


web_dir = Path(__file__).parent.parent / "web"
app.mount(
    "/static",
    _CachedStaticFiles(directory=str(web_dir / "static")),
    name="static",
)


# Browsers request /favicon.ico unconditionally; serve the brand logo so the
# devtools console isn't littered with 404s and so Render logs stay clean.
@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
    return FileResponse(
        str(web_dir / "static" / "brand-logo.png"),
        media_type="image/png",
        headers={"Cache-Control": "public, max-age=86400"},
    )

# Output artifacts (screenshots, logs)
output_dir = Path(__file__).parent.parent.parent / "output"
output_dir.mkdir(parents=True, exist_ok=True)
app.mount("/output", StaticFiles(directory=str(output_dir)), name="output")

# Desktop public downloads (DMG package)
desktop_releases_dir = Path(__file__).parent.parent.parent / "desktop" / "releases"
desktop_releases_dir.mkdir(parents=True, exist_ok=True)
app.mount("/downloads", StaticFiles(directory=str(desktop_releases_dir)), name="downloads")

# Templates
templates = Jinja2Templates(directory=str(web_dir / "templates"))
app_name = (os.getenv("APP_NAME", "Design Studio Hub") or "Design Studio Hub").strip()
# Product name: distinto da app_name (workspace brand). Usato nell'appbar e nel
# <title> tag del browser. app_name resta per sidebar logo + footer. Override
# via env var PRODUCT_NAME.
product_name = (os.getenv("PRODUCT_NAME", "AI Testing Platform") or "AI Testing Platform").strip()
app_version = (os.getenv("APP_VERSION", app.version) or app.version).strip()
templates.env.globals["app_name"] = app_name
templates.env.globals["product_name"] = product_name
templates.env.globals["app_version"] = app_version
# Fingerprint statico per cache-busting su CSS/JS critici (base.html li
# include come `?v={{ asset_v }}`). Calcolato una volta al boot — il
# container restart su HF dopo un deploy genera un nuovo hash, forzando
# il refresh client-side senza dover bumpare manualmente app_version.
templates.env.globals["asset_v"] = _compute_asset_version(web_dir / "static")
# Espongo `enforce_auth` ai template così il client JS può saltare il
# guard di redirect-to-login quando il server ha disabilitato l'auth
# (caso dev locale: il guard altrimenti redirigerebbe in loop perché
# Supabase non è configurato e non c'è modo legittimo di ottenere un
# token).
from src.utils.env import env_bool as _env_bool

templates.env.globals["enforce_auth"] = _env_bool("ENFORCE_AUTH", False)

# i18n globali — dizionario traduzioni UI accessibile nei template come `t`
try:
    from src.web.i18n import get_translations as _get_translations

    templates.env.globals["t"] = _get_translations(os.getenv("UI_LOCALE", "it"))
except Exception:  # pragma: no cover — fallback se i18n non caricabile
    templates.env.globals["t"] = {}


def _env_bool(name: str, default: bool = False) -> bool:
    value = os.getenv(name)
    if value is None:
        return default
    return str(value).strip().lower() in {"1", "true", "yes", "on"}


def _coerce_bool(value: object, default: bool = False) -> bool:
    if isinstance(value, bool):
        return value
    if value is None:
        return default
    if isinstance(value, (int, float)):
        return bool(value)
    if isinstance(value, str):
        lowered = value.strip().lower()
        if lowered in {"1", "true", "yes", "on"}:
            return True
        if lowered in {"0", "false", "no", "off", ""}:
            return False
    return default


def _env_int(name: str, default: int) -> int:
    try:
        return int(str(os.getenv(name, str(default))).strip())
    except Exception:
        return default


def _load_desktop_release_feed() -> dict:
    """Fetch desktop release metadata from remote JSON feed (optional)."""
    feed_url = os.getenv("DESKTOP_APP_UPDATE_FEED_URL", "").strip()
    if not feed_url:
        return {}

    try:
        req = UrlRequest(feed_url, headers={"User-Agent": "AiTestingPlatform/desktop-feed"})
        with urlopen(req, timeout=8) as response:  # noqa: S310 — URL from operator-controlled env
            status = int(getattr(response, "status", 0) or 0)
            if status < 200 or status >= 300:
                return {}
            body = response.read().decode("utf-8", errors="ignore")
            payload = json.loads(body)
            if not isinstance(payload, dict):
                return {}
            return payload
    except (HTTPError, URLError, TimeoutError, json.JSONDecodeError):
        return {}
    except Exception:
        return {}


@app.get("/", response_class=HTMLResponse)
async def root(request: Request):
    """Serve the main dashboard."""
    return templates.TemplateResponse(
        "dashboard.html", {"request": request, "active_page": "dashboard"}
    )


@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard(request: Request):
    """Serve the dashboard page."""
    return templates.TemplateResponse(
        "dashboard.html", {"request": request, "active_page": "dashboard"}
    )


@app.get("/bots", response_class=HTMLResponse)
async def bots_page(request: Request):
    """Serve the bots page."""
    return templates.TemplateResponse("bots.html", {"request": request, "active_page": "bots"})


@app.get("/personas", response_class=HTMLResponse)
async def personas_page(request: Request):
    """Serve the personas page."""
    return templates.TemplateResponse(
        "personas.html", {"request": request, "active_page": "personas"}
    )


@app.get("/scenarios", response_class=HTMLResponse)
async def scenarios_page(request: Request):
    """Serve the scenarios page."""
    return templates.TemplateResponse(
        "scenarios.html", {"request": request, "active_page": "scenarios"}
    )


@app.get("/knowledge-sources", response_class=HTMLResponse)
async def knowledge_sources_page(request: Request):
    """Serve the knowledge sources management page."""
    return templates.TemplateResponse(
        "knowledge_sources.html",
        {"request": request, "active_page": "knowledge_sources"},
    )


@app.get("/sessions", response_class=HTMLResponse)
async def sessions_page(request: Request):
    """Serve the sessions page."""
    from src.utils.feature_flags import wilson_session_verdict_enabled

    return templates.TemplateResponse(
        "sessions.html",
        {
            "request": request,
            "active_page": "sessions",
            "wilson_verdict_enabled": wilson_session_verdict_enabled(),
        },
    )


# Note: /reports is handled by reports_dashboard_router


@app.get("/profile", response_class=HTMLResponse)
async def profile_page(request: Request):
    """Serve the profile page."""
    return templates.TemplateResponse("profile.html", {"request": request})


@app.get("/sessions/report", response_class=HTMLResponse)
async def session_report_page(request: Request):
    """Serve the session report page."""
    return templates.TemplateResponse(
        "session_report.html", {"request": request, "active_page": "sessions"}
    )


@app.get("/sessions/{session_id}/turns", response_class=HTMLResponse)
async def session_turns_page(request: Request, session_id: str):
    """Per-turn correctness view with AIS labels, evidence and override action."""
    return templates.TemplateResponse(
        "session_turns.html",
        {"request": request, "active_page": "sessions", "session_id": session_id},
    )


@app.get("/sessions/{session_id}/config", response_class=HTMLResponse)
async def session_config_page(request: Request, session_id: str):
    """Pre-run configuration: prompt editor + model overrides + 'Esegui' action."""
    return templates.TemplateResponse(
        "session_config.html",
        {"request": request, "active_page": "sessions", "session_id": session_id},
    )


@app.get("/evaluations", response_class=HTMLResponse)
async def evaluations_page(request: Request):
    """Serve the evaluations page."""
    return templates.TemplateResponse(
        "evaluations.html", {"request": request, "active_page": "sessions"}
    )


@app.get("/manual-test", response_class=HTMLResponse)
async def manual_test_page(request: Request):
    """Serve the manual test page."""
    return templates.TemplateResponse(
        "manual_test.html", {"request": request, "active_page": "manual_test"}
    )


# Auth Pages
@app.get("/auth/login", response_class=HTMLResponse)
async def login_page(request: Request):
    """Serve the login page."""
    return templates.TemplateResponse("auth/login.html", {"request": request})


@app.get("/auth/register", response_class=HTMLResponse)
async def register_page(request: Request):
    """Serve the register page - Disabled, admin only"""
    # Redirect to login since registration is admin-only
    return templates.TemplateResponse("auth/login.html", {"request": request})


@app.get("/admin/users", response_class=HTMLResponse)
async def admin_users_page(request: Request):
    """Serve the admin users management page.

    Auth enforcement è **lato client** (vedi blocco JS nel template che
    reindirizza a /auth/login se non c'è token e a / se il ruolo non è
    superadmin). Il server-side guard precedente cercava il bearer
    nell'header `Authorization`, ma il browser non lo manda mai sulle
    navigazioni `<a href>` (l'header è esclusiva di `fetch()` con
    `Authorization` settato in JS). Quel guard finiva sempre in
    redirect → loop login. Le API mutanti sono già protette via
    `require_superadmin` nei router (routes/auth.py, routes/admin_*).
    """
    return templates.TemplateResponse(
        "admin/users.html", {"request": request, "active_page": "users"}
    )


@app.get("/admin/settings", response_class=HTMLResponse)
async def admin_settings_page(request: Request):
    """Serve the admin settings page.

    Auth enforcement è **lato client** (vedi blocco JS nel template).
    Vedi nota su /admin/users per il rationale.
    """
    return templates.TemplateResponse(
        "admin/settings.html", {"request": request, "active_page": "settings"}
    )


@app.get("/workspaces", response_class=HTMLResponse)
async def workspaces_page(request: Request):
    """Serve the workspaces management page."""
    return templates.TemplateResponse(
        "workspaces.html", {"request": request, "active_page": "workspaces"}
    )


@app.get("/bug-tickets", response_class=HTMLResponse)
async def bug_tickets_page(request: Request):
    """Serve the bug tickets page."""
    return templates.TemplateResponse(
        "bug_tickets.html", {"request": request, "active_page": "bug_tickets"}
    )


@app.get("/health")
async def health_check():
    """Health check endpoint — DB liveness + Supabase + AI provider config.

    Returns HTTP 503 if the application database is unreachable so that the
    Render orchestrator and any uptime probe can detect a hard outage. Other
    components (Supabase, AI provider) are reported but do not flip the
    overall status — they may be intentionally unconfigured in dev.
    """
    from sqlalchemy import text

    # 1) Application DB — required.
    db_status: str = "unknown"
    db_ok = False
    try:
        from src.db import get_db

        instance = get_db()
        with instance.get_session() as session:
            session.execute(text("SELECT 1"))
        db_status = "ok"
        db_ok = True
    except Exception:
        logger.exception("healthcheck: db unreachable")
        db_status = "unreachable"

    # 2) Supabase auth backend — optional in dev, expected in prod.
    supabase_status = "not_configured"
    try:
        from src.api.supabase_init import check_supabase_connection, init_supabase_tables

        if check_supabase_connection():
            supabase_status = "connected" if init_supabase_tables() else "awaiting_setup"
        else:
            supabase_status = "connection_failed"
    except Exception:
        logger.exception("healthcheck: supabase check failed")
        supabase_status = "error"

    # 3) AI provider key presence (no API call).
    provider = env_str("AI_PROVIDER", "openai").strip().lower()
    key_var = {
        "openai": "OPENAI_API_KEY",
        "groq": "GROQ_API_KEY",
        "kimi": "KIMI_API_KEY",
        "openrouter": "OPENROUTER_API_KEY",
    }.get(provider)
    ai_status = (
        ("configured" if env_str(key_var, "") else "missing_key")
        if key_var
        else f"provider_{provider}"
    )

    payload = {
        "status": "ok" if db_ok else "critical",
        "version": app.version,
        "db": db_status,
        "supabase": supabase_status,
        "ai_provider": ai_status,
        "production": _PRODUCTION,
    }
    return JSONResponse(status_code=200 if db_ok else 503, content=payload)


@app.get("/api/desktop/latest")
async def desktop_latest_release(request: Request):
    """Return latest desktop release metadata for in-app guided updates."""
    feed_payload = _load_desktop_release_feed()

    latest_version = str(
        feed_payload.get("latest_version") or os.getenv("DESKTOP_APP_LATEST_VERSION", "").strip()
    ).strip()
    download_url = str(
        feed_payload.get("download_url") or os.getenv("DESKTOP_APP_DOWNLOAD_URL", "").strip()
    ).strip()
    if not download_url:
        default_pkg = (
            os.getenv("DESKTOP_APP_DEFAULT_FILENAME", "Ai-Testing-Platform-macos-arm64.dmg") or ""
        ).strip()
        fallback_file = desktop_releases_dir / default_pkg
        if default_pkg and fallback_file.exists():
            public_base = (os.getenv("PUBLIC_BASE_URL", "") or "").strip().rstrip("/")
            if public_base:
                download_url = f"{public_base}/downloads/{default_pkg}"
            else:
                base = str(request.base_url).rstrip("/")
                download_url = f"{base}/downloads/{default_pkg}"
    release_notes_url = str(
        feed_payload.get("release_notes_url")
        or os.getenv("DESKTOP_APP_RELEASE_NOTES_URL", "").strip()
    ).strip()
    min_supported_version = str(
        feed_payload.get("min_supported_version")
        or os.getenv("DESKTOP_APP_MIN_VERSION", "").strip()
    ).strip()
    channel = str(
        feed_payload.get("channel")
        or os.getenv("DESKTOP_APP_CHANNEL", "stable").strip()
        or "stable"
    ).strip()
    mandatory = _coerce_bool(
        feed_payload.get("mandatory"),
        default=_env_bool("DESKTOP_APP_UPDATE_MANDATORY", default=False),
    )
    auto_download = _coerce_bool(
        feed_payload.get("auto_download"),
        default=_env_bool("DESKTOP_APP_AUTO_DOWNLOAD", default=False),
    )
    auto_install = _coerce_bool(
        feed_payload.get("auto_install"),
        default=_env_bool("DESKTOP_APP_AUTO_INSTALL", default=True),
    )
    poll_interval_seconds = int(
        feed_payload.get("poll_interval_seconds")
        if str(feed_payload.get("poll_interval_seconds") or "").strip().isdigit()
        else _env_int("DESKTOP_APP_POLL_INTERVAL_SECONDS", 1800)
    )

    enabled = bool(
        latest_version
        and download_url
        and (download_url.startswith("http://") or download_url.startswith("https://"))
    )
    return {
        "enabled": enabled,
        "source": "feed" if feed_payload else "env",
        "feed_url": os.getenv("DESKTOP_APP_UPDATE_FEED_URL", "").strip(),
        "channel": channel,
        "latest_version": latest_version if enabled else "",
        "download_url": download_url if enabled else "",
        "release_notes_url": release_notes_url,
        "min_supported_version": min_supported_version,
        "mandatory": mandatory,
        "auto_download": auto_download,
        "auto_install": auto_install,
        "poll_interval_seconds": max(60, min(poll_interval_seconds, 86400)),
    }


@app.get("/api/desktop/download/latest")
async def desktop_download_latest(request: Request):
    """Stable endpoint that redirects to configured desktop package URL, or serves local fallback."""
    configured = (os.getenv("DESKTOP_APP_DOWNLOAD_URL", "") or "").strip()
    if configured and configured.startswith(("http://", "https://")):
        configured_parsed = urlparse(configured)
        configured_path = (configured_parsed.path or "").rstrip("/")
        request_parsed = urlparse(str(request.url))
        request_path = (request_parsed.path or "").rstrip("/")
        same_target = (
            configured_parsed.scheme == request_parsed.scheme
            and configured_parsed.netloc == request_parsed.netloc
            and configured_path == request_path
        )
        # Guard against redirect loops from self-referential API URLs.
        points_to_api = configured_path in {"/api/desktop/download/latest", "/api/desktop/latest"}
        if not same_target and not points_to_api:
            return RedirectResponse(url=configured, status_code=307)

    default_pkg = (
        os.getenv("DESKTOP_APP_DEFAULT_FILENAME", "Ai-Testing-Platform-macos-arm64.dmg") or ""
    ).strip()
    fallback_file = desktop_releases_dir / default_pkg
    if default_pkg and fallback_file.exists():
        media = "application/x-apple-diskimage"
        return FileResponse(
            path=str(fallback_file),
            media_type=media,
            filename=default_pkg,
        )

    return JSONResponse(
        status_code=404,
        content={
            "error": "desktop_package_not_found",
            "message": "No desktop package available at the configured location.",
        },
    )


@app.get("/health/bots")
async def bots_health_check():
    """Check if target bots (Duolly) are reachable."""
    import httpx

    from src.db import BotRepository, get_db

    results = []

    try:
        db = get_db()
        with db.get_session() as session:
            repo = BotRepository(session)
            bots = repo.list_all(active_only=True)

            for bot in bots:
                bot_url = str(bot.url)
                try:
                    # Quick HEAD request to check if site is up
                    async with httpx.AsyncClient(timeout=10.0, follow_redirects=True) as client:
                        response = await client.head(bot_url)
                        status = (
                            "up" if response.status_code < 500 else f"error_{response.status_code}"
                        )
                except httpx.TimeoutException:
                    status = "timeout"
                except httpx.ConnectError:
                    status = "unreachable"
                except Exception as e:
                    status = f"error: {str(e)[:30]}"

                results.append(
                    {"id": str(bot.id), "name": bot.name, "url": bot_url, "status": status}
                )
    except Exception as e:
        return {"status": "error", "message": f"Failed to check bots: {str(e)}"}

    # Overall status
    all_up = all(r["status"] == "up" for r in results)
    any_down = any(r["status"] in ["timeout", "unreachable", "error"] for r in results)

    return {
        "status": "ok" if all_up else "degraded" if not any_down else "critical",
        "bots_checked": len(results),
        "bots_up": sum(1 for r in results if r["status"] == "up"),
        "bots_down": sum(1 for r in results if r["status"] not in ["up", "unknown"]),
        "details": results,
    }


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)