File size: 97,058 Bytes
95c3d39
1c3d9cb
 
01ad838
1c3d9cb
 
95c3d39
 
 
 
c753231
 
 
 
a50ed01
c753231
95c3d39
c753231
01ad838
c7dcb8d
 
01ad838
 
1c3d9cb
 
 
 
 
01ad838
95c3d39
1c3d9cb
 
 
 
 
 
 
f5968a9
 
 
 
 
95c3d39
371a747
1c3d9cb
 
59e386f
1c3d9cb
 
 
f5968a9
 
 
 
 
1c3d9cb
 
4ceccae
 
 
 
 
 
 
 
 
 
 
 
1c3d9cb
5c260b7
1c3d9cb
5c260b7
 
59e386f
 
5c260b7
59e386f
5c260b7
1c3d9cb
5c260b7
 
385ba13
59e386f
385ba13
 
5c260b7
 
2cc417c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3d9cb
27c7e36
1c3d9cb
01ad838
 
8a74dde
1178ac8
 
 
 
1fc9e89
1178ac8
1fc9e89
 
 
1178ac8
 
1fc9e89
 
1178ac8
 
 
fe821a3
 
 
 
 
 
 
 
 
 
 
 
 
 
0be0920
fe821a3
 
 
 
 
 
 
 
0be0920
fe821a3
 
 
 
 
0be0920
fe821a3
 
 
 
 
 
 
 
 
0be0920
 
fe821a3
 
 
 
 
0be0920
fe821a3
 
0be0920
fe821a3
0be0920
 
fe821a3
 
 
0be0920
fe821a3
 
 
0be0920
fe821a3
 
 
 
 
 
1178ac8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fc9e89
1178ac8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4a56b9
1178ac8
 
 
 
 
b4a56b9
1178ac8
 
 
 
 
 
 
 
 
03643ba
 
 
1178ac8
03643ba
 
 
1178ac8
03643ba
 
 
1178ac8
03643ba
 
 
1178ac8
 
 
03643ba
 
 
 
b4a56b9
1178ac8
 
 
03643ba
0be0920
03643ba
b4a56b9
1178ac8
 
03643ba
1178ac8
 
 
 
 
 
f5968a9
f1c70d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a040b95
 
 
 
 
 
 
 
 
f1c70d4
 
a040b95
 
f1c70d4
 
a040b95
 
f1c70d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7dcb8d
f1c70d4
 
 
 
 
 
 
 
 
 
 
 
 
1c3d9cb
 
80bd48a
 
 
 
 
 
 
 
 
 
 
5c260b7
95c3d39
5c260b7
1c3d9cb
95c3d39
1c3d9cb
5c260b7
 
 
 
 
 
 
09cebf1
 
80bd48a
 
5c260b7
95c3d39
8316b56
da4a83b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0be0920
da4a83b
 
0be0920
da4a83b
0be0920
 
da4a83b
 
 
 
 
0be0920
09cebf1
da4a83b
 
0be0920
09cebf1
 
0be0920
80bd48a
1c3d9cb
 
 
5c260b7
1c3d9cb
 
80bd48a
09cebf1
0be0920
5c260b7
1c3d9cb
 
 
95c3d39
 
1c3d9cb
f5968a9
1c3d9cb
01ad838
f5968a9
 
 
 
 
 
 
 
1c3d9cb
 
01ad838
1c3d9cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371a747
 
1c3d9cb
f5968a9
1c3d9cb
01ad838
f5968a9
 
 
 
 
 
 
 
1c3d9cb
 
95c3d39
1c3d9cb
 
 
 
95c3d39
1c3d9cb
 
cc57658
1c3d9cb
 
 
 
 
95c3d39
 
371a747
1c3d9cb
 
4ceccae
 
 
 
 
c7dcb8d
4ceccae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3d9cb
 
 
 
95c3d39
1c3d9cb
 
 
 
 
 
 
 
 
8316b56
 
1c3d9cb
95c3d39
1c3d9cb
 
 
 
 
 
 
371a747
1c3d9cb
 
 
 
 
 
95c3d39
 
371a747
95c3d39
 
 
371a747
 
 
 
95c3d39
371a747
 
 
95c3d39
371a747
 
95c3d39
371a747
 
27c7e36
95c3d39
371a747
95c3d39
27c7e36
 
 
 
 
 
371a747
27c7e36
 
 
 
 
 
 
 
 
 
 
371a747
 
 
 
 
 
27c7e36
371a747
27c7e36
95c3d39
 
371a747
27c7e36
371a747
95c3d39
27c7e36
 
 
 
 
 
371a747
 
c42c638
27c7e36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95c3d39
 
371a747
 
 
 
 
 
 
27c7e36
95c3d39
371a747
 
 
 
 
 
 
 
95c3d39
371a747
 
 
95c3d39
 
371a747
 
 
 
95c3d39
371a747
 
 
95c3d39
 
 
 
 
371a747
95c3d39
 
371a747
95c3d39
 
 
 
371a747
95c3d39
371a747
95c3d39
371a747
 
 
27c7e36
95c3d39
 
371a747
 
95c3d39
 
1c3d9cb
 
 
 
 
95c3d39
 
1c3d9cb
371a747
 
 
 
1c3d9cb
 
 
 
 
 
 
 
 
371a747
95c3d39
1c3d9cb
 
 
 
 
371a747
1c3d9cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371a747
1c3d9cb
371a747
1c3d9cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371a747
1c3d9cb
4ceccae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3d9cb
371a747
 
 
1c3d9cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371a747
1c3d9cb
371a747
 
 
 
1c3d9cb
371a747
 
 
 
 
 
1c3d9cb
371a747
 
 
 
 
1c3d9cb
371a747
1c3d9cb
371a747
 
 
 
1c3d9cb
371a747
 
 
 
 
 
1c3d9cb
371a747
 
 
 
1c3d9cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80bd48a
1c3d9cb
80bd48a
1c3d9cb
 
80bd48a
 
 
 
 
 
 
1c3d9cb
 
 
 
371a747
 
 
 
27c7e36
371a747
 
27c7e36
 
 
 
 
 
 
 
371a747
 
27c7e36
 
371a747
58da051
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
983da25
 
 
c42c638
 
 
 
 
 
 
 
 
 
983da25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371a747
27c7e36
 
 
 
371a747
 
 
95c3d39
58da051
95c3d39
 
27c7e36
371a747
c7dcb8d
371a747
 
 
 
f5968a9
27c7e36
f5968a9
 
27c7e36
 
 
 
c7dcb8d
27c7e36
 
1c3d9cb
 
 
27c7e36
 
 
 
 
 
 
 
 
95c3d39
371a747
c7dcb8d
 
 
 
 
 
 
 
371a747
 
 
073ec60
011da86
f43e798
011da86
 
f43e798
011da86
 
 
 
95c3d39
371a747
 
 
 
 
c7dcb8d
371a747
27c7e36
c7dcb8d
371a747
27c7e36
95c3d39
c7dcb8d
 
95c3d39
371a747
95c3d39
c753231
 
 
 
 
 
 
 
 
 
c42c638
c753231
 
 
c42c638
 
 
 
c753231
c42c638
c753231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5ce785
 
 
eb9eeb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ec58ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76a7bdf
e5ce785
 
 
 
 
76a7bdf
e5ce785
 
76a7bdf
e5ce785
 
 
 
 
 
 
76a7bdf
 
e5ce785
76a7bdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5ce785
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76a7bdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ec58ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb9eeb8
 
a2fbb2c
 
 
eb9eeb8
0ec58ee
eb9eeb8
0ec58ee
 
 
 
 
 
 
 
 
 
 
a2fbb2c
0ec58ee
 
a2fbb2c
 
 
 
0ec58ee
a2fbb2c
 
0ec58ee
a2fbb2c
 
 
0ec58ee
a2fbb2c
0ec58ee
 
 
 
 
a2fbb2c
 
0ec58ee
 
 
 
 
 
a2fbb2c
 
 
0ec58ee
a2fbb2c
0ec58ee
 
 
a2fbb2c
 
0ec58ee
a2fbb2c
0ec58ee
 
 
a2fbb2c
0ec58ee
 
 
 
 
a2fbb2c
 
0ec58ee
 
 
 
 
 
 
76a7bdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ec58ee
76a7bdf
 
 
 
 
 
c753231
 
f5968a9
c753231
fe821a3
 
 
58da051
49fffa7
 
76a7bdf
 
f1c70d4
49fffa7
 
1178ac8
49fffa7
 
 
 
76a7bdf
 
f1c70d4
49fffa7
 
1178ac8
49fffa7
 
76a7bdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49fffa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58da051
49fffa7
 
 
 
 
 
 
 
 
 
 
 
 
1178ac8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1c70d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49fffa7
 
 
 
 
 
 
58da051
49fffa7
 
 
c7dcb8d
58da051
b6fab60
c753231
c42c638
d94e908
 
 
 
c42c638
d94e908
c753231
76a7bdf
 
b6fab60
f1c70d4
b6fab60
 
1178ac8
b6fab60
 
 
76a7bdf
b6fab60
f1c70d4
b6fab60
 
1178ac8
b6fab60
 
 
c42c638
 
 
 
 
 
 
 
 
c753231
 
 
 
 
09cebf1
c753231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58da051
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c753231
 
 
 
 
 
 
 
 
 
c42c638
 
 
 
 
 
c753231
76a7bdf
 
f1c70d4
 
 
 
 
 
58da051
c753231
95c3d39
01ad838
c753231
 
01ad838
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
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
"""
CROVIA REGISTRY OBSERVER v3.0.0
Truth Surface for TPR (Training Provenance Registry)

Displays ONLY verifiable data: observations, stats, merkle roots.
No scores. No badges. No violations. Evidence-first.
"""

import json
import hashlib
try:
    import gradio as gr
except Exception:
    gr = None
import requests
import re
from datetime import datetime, timezone
from typing import Dict, List, Any, Optional, Tuple

VERSION = "3.1.0"
PROTOCOL_VERSION = "v1.1"
TPR_API_URL = "https://registry.croviatrust.com"

# Truth Anchor - Registry source-of-truth only
REGISTRY_ENDPOINTS = [
    "/api/registry/stats",
    "/api/registry/merkle",
    "/api/registry/recent"
]


def load_registry_stats() -> Dict[str, Any]:
    """Load verifiable stats from TPR Registry."""
    try:
        response = requests.get(f"{TPR_API_URL}/api/registry/stats", timeout=5)
        if response.status_code == 200:
            return response.json()
        return {"error": f"HTTP {response.status_code}"}
    except requests.Timeout:
        return {"error": "Registry timeout (>5s)"}
    except Exception as e:
        return {"error": f"Registry unreachable: {type(e).__name__}"}


def load_merkle_root() -> Dict[str, Any]:
    """Load merkle root from TPR Registry."""
    try:
        response = requests.get(f"{TPR_API_URL}/api/registry/merkle", timeout=5)
        if response.status_code == 200:
            return response.json()
        return {"error": f"HTTP {response.status_code}"}
    except requests.Timeout:
        return {"error": "Timeout"}
    except Exception as e:
        return {"error": str(type(e).__name__)}


def load_merkle_timeline(limit: int = 10) -> List[Dict[str, Any]]:
    """Load merkle timeline from TPR Registry."""
    try:
        response = requests.get(f"{TPR_API_URL}/api/registry/merkle/timeline?limit={limit}", timeout=5)
        if response.status_code == 200:
            data = response.json()
            return data.get('timeline', [])
        return []
    except:
        return []


def load_recent_observations(limit: int = 12) -> List[Dict[str, Any]]:
    """Load diverse observations from TPR Registry - mix of recent + historical."""
    try:
        # Get targets with history (not just recent observations)
        response = requests.get(f"{TPR_API_URL}/api/targets/summary", timeout=5)
        if response.status_code == 200:
            data = response.json()
            targets = data.get('targets', [])
            
            # Filter out Crovia internal and test
            filtered = []
            for t in targets:
                target_id = t.get('target_id', '')
                if 'crovia' in target_id.lower():
                    continue
                if any(pattern in target_id.lower() for pattern in ['test-', 'debug-', 'demo-']):
                    continue
                filtered.append(t)
            
            def _parse_ts(s: Any) -> datetime:
                if not s:
                    return datetime(1970, 1, 1, tzinfo=timezone.utc)
                try:
                    return datetime.fromisoformat(str(s).replace('Z', '+00:00'))
                except Exception:
                    return datetime(1970, 1, 1, tzinfo=timezone.utc)

            recent_sorted = sorted(filtered, key=lambda x: _parse_ts(x.get('last_seen')), reverse=True)
            history_sorted = sorted(filtered, key=lambda x: int(x.get('days_monitored', 0) or 0), reverse=True)

            recent_n = max(1, int(limit) // 2)
            history_n = max(1, int(limit) - recent_n)

            out: List[Dict[str, Any]] = []
            seen: set[str] = set()

            for t in recent_sorted[:recent_n]:
                tid = t.get('target_id')
                if not tid or tid in seen:
                    continue
                out.append(t)
                seen.add(tid)

            for t in history_sorted:
                if len(out) >= int(limit):
                    break
                tid = t.get('target_id')
                if not tid or tid in seen:
                    continue
                out.append(t)
                seen.add(tid)

            return out[:limit]
        return []
    except:
        return []


HF_DISCLOSURE_INDEX_URL = "https://huggingface.co/datasets/Crovia/global-ai-training-omissions/resolve/main/open/reports/disclosure_index_latest.json"


def _load_disclosure_index() -> Optional[Dict[str, Any]]:
    """Load Disclosure Index from HuggingFace dataset."""
    import time
    try:
        # Add cache-busting parameter to avoid HuggingFace CDN caching
        url = f"{HF_DISCLOSURE_INDEX_URL}?t={int(time.time())}"
        r = requests.get(url, timeout=15, headers={"Cache-Control": "no-cache"})
        if r.status_code == 200:
            return r.json()
    except Exception as e:
        print(f"[CROVIA] Failed to load disclosure index: {e}")
    return None


def _load_verified_findings() -> Optional[Dict[str, Any]]:
    """Load verified forensic findings from HuggingFace dataset."""
    import time
    try:
        url = f"https://huggingface.co/datasets/Crovia/global-ai-training-omissions/raw/main/open/forensic/verified_findings.json?t={int(time.time())}"
        r = requests.get(url, timeout=10, headers={"Cache-Control": "no-cache"})
        if r.status_code == 200:
            return r.json()
    except Exception as e:
        print(f"[CROVIA] Failed to load verified findings: {e}")
    return None


def _generate_alert_html() -> str:
    """Generate HTML summary for documentation change observations (if any)."""
    findings = _load_verified_findings()
    if not findings:
        return ""
    
    verified = findings.get("verified_findings", [])
    if not verified:
        return ""
    
    # Build observation summary HTML
    generated = findings.get("generated_at", "")[:19].replace("T", " ")
    
    findings_rows = ""
    for f in verified[:5]:
        confidence = f.get("confidence", "UNKNOWN")
        conf_color = "#34d399" if confidence == "VERIFIED" else "#fbbf24" if confidence == "HIGH" else "#a1a1aa"
        
        findings_rows += f'''
        <div style="background:#1e1e3f;border-radius:8px;padding:12px;margin-bottom:8px;">
            <div style="display:flex;justify-content:space-between;align-items:center;">
                <span style="color:#ffffff;font-weight:700;">{f.get("date", "N/A")}</span>
                <span style="color:{conf_color};font-weight:700;font-size:12px;">{confidence} ({f.get("confidence_score", 0):.0f}%)</span>
            </div>
            <div style="color:#a1a1aa;font-size:12px;margin-top:4px;">
                {f.get("orgs_count", 0)} organizations • {f.get("event_count", 0)} events • 
                {f.get("details", {}).get("license_removals", 0)} license changes • 
                {f.get("details", {}).get("dataset_removals", 0)} dataset declaration changes
            </div>
        </div>
        '''
    
    return f'''
    <div style="background:linear-gradient(135deg,#7c3aed 0%,#6D28D9 100%);border-radius:16px;padding:3px;margin:12px 0;">
        <div style="background:#0f0f1a;border-radius:14px;padding:20px;">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;">
                <span style="font-size:24px;">�</span>
                <div>
                    <div style="color:#ffffff;font-weight:800;font-size:16px;">DOCUMENTATION CHANGES OBSERVED</div>
                    <div style="color:#a78bfa;font-size:12px;">Transparency Observatory • {generated} UTC</div>
                </div>
            </div>
            <div style="color:#e5e5e5;font-size:13px;margin-bottom:12px;">
                {len(verified)} observation(s) passed quality filtering checks.
            </div>
            {findings_rows}
            <div style="color:#71717a;font-size:11px;font-style:italic;margin-top:12px;">
                Observations are filtered for quality. Temporal sequence does not imply causation.
            </div>
        </div>
    </div>
    '''


def _fmt_num(n: Any) -> str:
    """Format number with K/M suffix."""
    if n is None:
        return "N/A"
    try:
        n = int(n)
        if n >= 1_000_000:
            return f"{n/1_000_000:.1f}M"
        if n >= 1_000:
            return f"{n/1_000:.1f}K"
        return str(n)
    except:
        return str(n)


def _generate_index_html() -> str:
    """Generate HTML for Disclosure Index display."""
    index = _load_disclosure_index()
    if not index:
        return '<div style="color:#f87171;padding:20px;background:#1a1a2e;border-radius:12px;">⚠️ Unable to load Disclosure Index from HuggingFace. The data may be temporarily unavailable. Click Refresh to retry.</div>'
    
    week_id = index.get("week_id", "Unknown")
    generated_at = index.get("generated_at", "")[:19].replace("T", " ")
    coverage = index.get("coverage", {})
    obs = index.get("disclosure_observations", {})
    pop = index.get("popularity_observations", {})
    orgs = index.get("by_organization", [])[:8]
    
    training = obs.get("training_section", {})
    declared = obs.get("declared_datasets", {})
    license_obs = obs.get("license", {})
    readme = obs.get("readme_access", {})
    
    # Build org rows
    org_rows = ""
    for org in orgs:
        org_name = org.get("organization", "")
        org_targets = org.get("targets_monitored", 0)
        org_training = org.get("training_section_present", 0)
        training_pct = round(100 * org_training / org_targets, 0) if org_targets > 0 else 0
        org_rows += f'<tr><td style="color:#e5e5e5 !important;font-weight:600;padding:8px 12px;">{org_name}</td><td style="color:#ffffff !important;text-align:center;padding:8px 12px;">{org_targets}</td><td style="color:#34d399 !important;text-align:center;padding:8px 12px;font-weight:600;">{org_training} ({training_pct:.0f}%)</td></tr>'
    
    # Build high-download rows
    high_dl = pop.get("high_download_training_absent", [])[:5]
    high_dl_rows = ""
    for t in high_dl:
        high_dl_rows += f'<tr><td style="color:#e5e5e5 !important;padding:8px 12px;">{t.get("target_id", "")}</td><td style="color:#fbbf24 !important;font-weight:700;text-align:right;padding:8px 12px;">{_fmt_num(t.get("downloads"))}</td></tr>'
    
    html = f'''
    <div style="background:#1a1a2e;border-radius:16px;padding:24px;margin:12px 0;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
            <div style="color:#fbbf24;font-weight:800;font-size:18px;">Week {week_id}</div>
            <div style="color:#71717a;font-size:12px;">Generated {generated_at} UTC</div>
        </div>
        
        <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px;">
            <div style="background:#262640;border-radius:12px;padding:20px;text-align:center;">
                <div style="color:#e5e5e5;font-size:13px;font-weight:600;margin-bottom:8px;letter-spacing:0.05em;">TARGETS</div>
                <div style="color:#ffffff;font-size:28px;font-weight:800;">{coverage.get("targets_monitored", 0)}</div>
            </div>
            <div style="background:#262640;border-radius:12px;padding:20px;text-align:center;">
                <div style="color:#e5e5e5;font-size:13px;font-weight:600;margin-bottom:8px;letter-spacing:0.05em;">TRAINING SECTION</div>
                <div style="color:#34d399;font-size:28px;font-weight:800;">{training.get("present_pct", 0)}%</div>
            </div>
            <div style="background:#262640;border-radius:12px;padding:20px;text-align:center;">
                <div style="color:#e5e5e5;font-size:13px;font-weight:600;margin-bottom:8px;letter-spacing:0.05em;">DECLARED DATASETS</div>
                <div style="color:#60a5fa;font-size:28px;font-weight:800;">{declared.get("with_declaration_pct", 0)}%</div>
            </div>
            <div style="background:#262640;border-radius:12px;padding:20px;text-align:center;">
                <div style="color:#e5e5e5;font-size:13px;font-weight:600;margin-bottom:8px;letter-spacing:0.05em;">GATED</div>
                <div style="color:#fb7185;font-size:28px;font-weight:800;">{pop.get("gated_pct", 0)}%</div>
            </div>
        </div>
        
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;">
            <div style="background:#262640;border-radius:12px;padding:16px;">
                <div style="color:#a78bfa;font-weight:700;font-size:14px;margin-bottom:16px;">BY ORGANIZATION</div>
                <table style="width:100%;font-size:13px;border-collapse:collapse;">
                    <tr style="border-bottom:1px solid #3f3f5a;"><th style="color:#ffffff !important;text-align:left;padding:8px 12px;font-weight:700;">Org</th><th style="color:#ffffff !important;text-align:center;padding:8px 12px;font-weight:700;">Targets</th><th style="color:#ffffff !important;text-align:center;padding:8px 12px;font-weight:700;">Training</th></tr>
                    {org_rows}
                </table>
            </div>
            <div style="background:#262640;border-radius:12px;padding:16px;">
                <div style="color:#fbbf24;font-weight:700;font-size:14px;margin-bottom:16px;">HIGH DOWNLOADS · DOCUMENTATION COVERAGE</div>
                <table style="width:100%;font-size:13px;border-collapse:collapse;">
                    <tr style="border-bottom:1px solid #3f3f5a;"><th style="color:#ffffff !important;text-align:left;padding:8px 12px;font-weight:700;">Target</th><th style="color:#ffffff !important;text-align:right;padding:8px 12px;font-weight:700;">Downloads</th></tr>
                    {high_dl_rows}
                </table>
                <div style="color:#a1a1aa;font-size:11px;margin-top:12px;font-style:italic;">Factual observation only. No judgment.</div>
            </div>
        </div>
    </div>
    '''
    return html


HF_TPA_URL = "https://registry.croviatrust.com/registry/data/tpa_latest.json"


def _load_tpa_latest() -> Optional[Dict[str, Any]]:
    """Load latest TPA data from registry."""
    import time
    try:
        url = f"{HF_TPA_URL}?t={int(time.time())}"
        r = requests.get(url, timeout=10, headers={"Cache-Control": "no-cache"})
        if r.status_code == 200:
            return r.json()
    except Exception as e:
        print(f"[CROVIA] Failed to load TPA data: {e}")
    return None


def _generate_tpa_panel_html() -> str:
    """Generate TPA panel HTML for the Space."""
    data = _load_tpa_latest()
    if not data or not data.get('tpas'):
        return '''<div style="background:#1a1a2e;border-radius:16px;padding:40px;text-align:center;margin:12px 0;">
            <div style="color:#f59e0b;font-size:18px;font-weight:700;margin-bottom:12px;">TPA data not yet available</div>
            <div style="color:#71717a;font-size:13px;">Temporal Proofs of Absence will appear here after the observer generates them.<br>Check back after the next hourly observation cycle.</div>
        </div>'''

    tpas = data['tpas']
    total = data.get('total_tpas', len(tpas))
    chain_h = data.get('chain_height', '--')

    # Fetch total monitored from registry to stay aligned with TPA page
    total_monitored = '--'
    try:
        sr = requests.get(f"{TPR_API_URL}/registry/data/search_targets.json", timeout=5)
        if sr.status_code == 200:
            total_monitored = sr.json().get('total', '--')
    except Exception:
        pass

    stats_html = f'''<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px;">
        <div style="background:#262640;border-radius:12px;padding:20px;text-align:center;">
            <div style="color:#60a5fa;font-size:28px;font-weight:800;">{total_monitored}</div>
            <div style="color:#a1a1aa;font-size:11px;text-transform:uppercase;letter-spacing:1px;">Total Monitored</div>
        </div>
        <div style="background:#262640;border-radius:12px;padding:20px;text-align:center;">
            <div style="color:#f59e0b;font-size:28px;font-weight:800;">{total}</div>
            <div style="color:#a1a1aa;font-size:11px;text-transform:uppercase;letter-spacing:1px;">TPAs Generated</div>
        </div>
        <div style="background:#262640;border-radius:12px;padding:20px;text-align:center;">
            <div style="color:#34d399;font-size:28px;font-weight:800;">{chain_h}</div>
            <div style="color:#a1a1aa;font-size:11px;text-transform:uppercase;letter-spacing:1px;">Chain Height</div>
        </div>
        <div style="background:#262640;border-radius:12px;padding:20px;text-align:center;">
            <div style="color:#a78bfa;font-size:28px;font-weight:800;">11</div>
            <div style="color:#a1a1aa;font-size:11px;text-transform:uppercase;letter-spacing:1px;">Jurisdictions</div>
        </div>
    </div>'''

    cards_html = ""
    for tpa in tpas[:12]:
        obs = tpa.get('observations', [])
        absent = [o for o in obs if not o.get('is_present')]
        present = [o for o in obs if o.get('is_present')]
        jurs = tpa.get('jurisdiction_exposures', [])
        ts = tpa.get('observation_timestamp', '')[:19].replace('T', ' ')
        anchor = tpa.get('temporal_anchor', {})
        merkle = tpa.get('merkle_root', '')[:24]

        absent_tags = ' '.join(
            f'<span style="padding:3px 8px;background:#FF450015;border:1px solid #FF4500;border-radius:5px;'
            f'font-size:11px;font-weight:600;color:#FF6347;font-family:monospace;"'
            f' title="{o.get("necessity_name", "")}">{o.get("necessity_id", "")}</span>'
            for o in absent
        )
        present_tags = ' '.join(
            f'<span style="padding:3px 8px;background:#00FF0010;border:1px solid #00880044;border-radius:5px;'
            f'font-size:11px;font-weight:600;color:#00AA00;font-family:monospace;"'
            f' title="{o.get("necessity_name", "")}">{o.get("necessity_id", "")}</span>'
            for o in present
        )
        jur_tags = ' '.join(
            f'<span style="padding:3px 8px;background:#8B5CF610;border:1px solid #8B5CF644;'
            f'border-radius:5px;font-size:10px;color:#A78BFA;">{j.get("jurisdiction_name", "")}</span>'
            for j in jurs
        )

        cards_html += f'''<div style="background:#0f0f1a;border:1px solid #1a1a2e;border-radius:12px;padding:20px;margin-bottom:14px;">
            <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:12px;flex-wrap:wrap;gap:8px;">
                <div>
                    <div style="color:#fff;font-size:16px;font-weight:600;word-break:break-all;">{tpa.get('model_id', '')}</div>
                    <div style="color:#444;font-size:10px;font-family:monospace;margin-top:2px;">{tpa.get('tpa_id', '')}</div>
                </div>
                <div style="color:#555;font-size:11px;font-family:monospace;">{ts} UTC</div>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px;">
                <div><div style="color:#666;font-size:10px;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px;">Absent ({tpa.get('absent_count', 0)})</div>{absent_tags}</div>
                <div><div style="color:#666;font-size:10px;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px;">Present ({tpa.get('present_count', 0)})</div>{present_tags}</div>
            </div>
            <div style="margin-bottom:12px;"><div style="color:#666;font-size:10px;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px;">Jurisdictions ({tpa.get('total_jurisdictions_exposed', 0)})</div>{jur_tags}</div>
            <div style="display:flex;justify-content:space-between;align-items:center;padding-top:12px;border-top:1px solid #1a1a2e;flex-wrap:wrap;gap:6px;">
                <span style="color:#444;font-size:10px;font-family:monospace;">Merkle: {merkle}...</span>
                <span style="color:#555;font-size:10px;background:#111;padding:3px 8px;border-radius:4px;border:1px solid #222;">Chain #{anchor.get('chain_height', 0)}</span>
                <a href="mailto:info@croviatrust.com" style="color:#8B5CF6 !important;font-size:10px;background:#8B5CF610;padding:3px 10px;border-radius:4px;border:1px solid #8B5CF644;text-decoration:none;font-weight:600;">Full proof &rarr; PRO</a>
            </div>
        </div>'''

    return f'''<div style="background:#1a1a2e;border-radius:16px;padding:24px;margin:12px 0;">
        {stats_html}
        {cards_html}
        <div style="color:#71717a;font-size:11px;text-align:center;margin-top:12px;">
            Pedersen commitments on secp256k1 &middot; Merkle SHA-256 &middot; Ed25519 signatures &middot;
            <a href="https://registry.croviatrust.com/registry/tpa" target="_blank" style="color:#8B5CF6 !important;">Full page &rarr;</a>
        </div>
    </div>'''


def generate_observation_cards_html() -> str:
    """Generate observation cards - VERIFIED DATA ONLY."""
    # Load temporal aggregates for days_monitored
    try:
        response = requests.get(f"{TPR_API_URL}/api/targets/summary", timeout=5)
        target_metrics = {}
        if response.status_code == 200:
            data = response.json()
            for t in data.get('targets', []):
                target_metrics[t['target_id']] = t
    except:
        target_metrics = {}
    
    targets = load_recent_observations(12)
    
    if not targets:
        return '<div class="error-box">No observations available</div>'
    
    cards = ""
    for target in targets:
        target_id = target.get('target_id', 'Unknown')
        tipo_target = target.get('tipo_target', 'unknown')
        days_monitored = target.get('days_monitored', 0)
        obs_count = target.get('observation_count', 0)
        latest_type = target.get('latest_type', 'unknown')
        last_seen = target.get('last_seen', '')
        absence_streak = target.get('absence_streak_days', 0)
        first_seen = target.get('first_seen', '')
        
        prefix = '📊 ' if tipo_target == 'dataset' else ''
        timestamp_display = last_seen[:19] if last_seen else 'N/A'
        
        # ABSENCE CLOCK - Temporal signal
        if latest_type == 'absence':
            streak = max(1, int(absence_streak) if str(absence_streak).isdigit() else 1)
            unit = "day" if streak == 1 else "days"

            if streak <= 6:
                band_label = "0–6"
                clock_color = "#fca5a5"
                note_color = "#94a3b8"
            elif streak <= 15:
                band_label = "7–15"
                clock_color = "#f59e0b"
                note_color = "#fbbf24"
            else:
                band_label = "16–30"
                clock_color = "#ef4444"
                note_color = "#fca5a5"

            clock_display = (
                f"<div style='color:{clock_color};font-weight:700;font-size:13px;margin-top:8px;'>"
                f"📊 {streak} {unit} since last documentation update"
                f"</div>"
            )
            temporal_note = (
                f"<div style='color:{note_color};font-size:11px;font-style:italic;margin-top:4px;'>"
                f"Observation ({band_label}d): documentation not updated in the last {streak} {unit}. "
                f"Verify timestamps via the Registry."
                f"</div>"
            )
        elif latest_type == 'presence' and days_monitored > 0:
            mon_unit = "day" if int(days_monitored) == 1 else "days"
            clock_display = f"<div style='color:#6b7280;font-size:12px;margin-top:8px;'>{days_monitored} {mon_unit} monitored</div>"
            temporal_note = "<div style='color:#94a3b8;font-size:11px;font-style:italic;margin-top:4px;'>Documentation present. Verify timestamps via the Registry.</div>"
        elif days_monitored > 0:
            mon_unit = "day" if int(days_monitored) == 1 else "days"
            clock_display = f"<div style='color:#6b7280;font-size:12px;margin-top:8px;'>{days_monitored} {mon_unit} monitored</div>"
            temporal_note = ""
        else:
            clock_display = "<div style='color:#6b7280;font-size:12px;margin-top:8px;'>First observation</div>"
            temporal_note = "<div style='color:#64748b;font-size:11px;font-style:italic;margin-top:4px;'>Insufficient temporal data for observation.</div>"
        
        cards += f'''
        <div class="observation-card">
            <div class="obs-header">
                <span class="obs-type">{latest_type.upper()}</span>
                <span class="obs-timestamp">{timestamp_display} UTC</span>
            </div>
            <div class="obs-target">{prefix}{target_id}</div>
            {clock_display}
            {temporal_note}
            <div class="obs-meta">Type: {tipo_target} · {obs_count} observations</div>
        </div>
        '''
    return cards


def generate_stats_box_html() -> str:
    """Generate registry stats box with error handling."""
    stats = load_registry_stats()
    
    if 'error' in stats:
        return f'''
        <div style="background:rgba(239,68,68,0.1);border:1px solid rgba(239,68,68,0.4);border-radius:12px;padding:16px;margin:12px 0;">
            <div style="color:#ef4444;font-weight:700;margin-bottom:8px;">⚠️ Registry Unreachable</div>
            <div style="color:#fca5a5;font-size:13px;">{stats['error']}</div>
        </div>
        '''
    
    if not stats:
        return '<div class="error-box">Stats unavailable</div>'
    
    total_obs = stats.get('total_observations', 0)
    today_obs = stats.get('observations_today_utc', 0)
    unique_targets = stats.get('unique_targets', 0)
    updated_at = stats.get('updated_at', 'N/A')
    latency = stats.get('latency_ms', 0)
    
    return f'''
    <div class="stats-box">
        <h3 class="stats-title">Registry Statistics</h3>
        <div class="stats-grid">
            <div class="stat-item">
                <div class="stat-value">{total_obs}</div>
                <div class="stat-label">Total Observations</div>
            </div>
            <div class="stat-item">
                <div class="stat-value">{today_obs}</div>
                <div class="stat-label">Today (UTC)</div>
            </div>
            <div class="stat-item">
                <div class="stat-value">{unique_targets}</div>
                <div class="stat-label">Unique Targets</div>
            </div>
        </div>
        <div class="stats-footer">
            Updated: {updated_at[:19]} UTC · Query: {latency}ms
        </div>
    </div>
    '''


def generate_merkle_box_html() -> str:
    """Generate merkle root box with error handling."""
    merkle = load_merkle_root()
    
    if 'error' in merkle:
        return f'''
        <div style="background:rgba(239,68,68,0.1);border:1px solid rgba(239,68,68,0.4);border-radius:12px;padding:16px;margin:12px 0;">
            <div style="color:#ef4444;font-weight:700;margin-bottom:8px;">⚠️ Merkle Root Unavailable</div>
            <div style="color:#fca5a5;font-size:13px;">{merkle['error']}</div>
        </div>
        '''
    
    if not merkle:
        return '<div class="error-box">Merkle root unavailable</div>'
    
    root = merkle.get('merkle_root', 'N/A')
    total_obs = merkle.get('total_observations', 0)
    algorithm = merkle.get('algorithm', 'N/A')
    computed_at = merkle.get('computed_at', 'N/A')
    
    return f'''
    <div class="merkle-box">
        <h3 class="merkle-title">Merkle Root <span style="color:#6b7280;font-size:11px;font-weight:400;">(cryptographic hash of all observations)</span></h3>
        <div class="merkle-hash">{root}</div>
        <div class="merkle-meta">
            Algorithm: {algorithm}<br>
            Observations: {total_obs}<br>
            Computed: {computed_at[:19]} UTC
        </div>
    </div>
    '''


def generate_merkle_timeline_html() -> str:
    """Generate merkle timeline box - VERIFIED DATA ONLY."""
    timeline = load_merkle_timeline(10)
    
    if not timeline:
        return '<div style="background:#0a0a12;border:1px solid #1a1a2e;border-radius:16px;padding:24px;text-align:center;color:#6B7280;font-size:13px;">Merkle timeline: endpoint not yet deployed. Current merkle root is available above.</div>'
    
    # Build timeline entries
    entries_html = ""
    for entry in reversed(timeline):  # Most recent first
        root = entry.get('merkle_root', 'N/A')[:16] + '...'  # Truncate for display
        total_obs = entry.get('total_observations', 0)
        computed_at = entry.get('computed_at', 'N/A')[:19]
        
        entries_html += f'''
        <div class="timeline-entry">
            <div class="timeline-time">{computed_at} UTC</div>
            <div class="timeline-hash">{root}</div>
            <div class="timeline-obs">{total_obs} observations</div>
        </div>
        '''
    
    return f'''
    <div class="merkle-timeline-box">
        <h3 class="merkle-title">Merkle Timeline (Last 10)</h3>
        <div class="timeline-entries">
            {entries_html}
        </div>
    </div>
    '''


def generate_truth_anchor_html() -> str:
    """Generate Truth Anchor - Registry source-of-truth only."""
    # Get current timestamp for temporal validity
    fetch_timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
    
    # Format endpoints list
    endpoints_list = "<br>".join([f"&nbsp;&nbsp;• {ep}" for ep in REGISTRY_ENDPOINTS])
    
    return f'''
    <div class="anchor-box">
        <h3 class="anchor-title">⚓ Truth Anchor</h3>
        <div class="anchor-section">
            <div class="anchor-label">Code Repository</div>
            <div class="anchor-value">
                <a href="https://github.com/croviatrust" target="_blank" class="anchor-link">https://github.com/croviatrust</a><br>
                <span style="color:#6B7280; font-size:11px;">Viewer-only Space. Registry backend not published here.</span>
            </div>
        </div>
        <div class="anchor-section">
            <div class="anchor-label">Registry Source-of-Truth</div>
            <div class="anchor-value">
                Base URL: <a href="{TPR_API_URL}" target="_blank" class="anchor-link">{TPR_API_URL}</a><br>
                Endpoints:<br>
                {endpoints_list}
            </div>
        </div>
        <div class="anchor-section">
            <div class="anchor-label">Temporal Validity</div>
            <div class="anchor-value">
                This Space reflects the registry state at last fetch.<br>
                Last fetch: {fetch_timestamp} UTC
            </div>
        </div>
    </div>
    '''

CSS = """
.gradio-container {
    max-width: 100% !important;
    padding: 0 !important;
    margin: 0 !important;
    background: #030305 !important;
}
.main, .contain, .wrap {
    max-width: 100% !important;
    padding: 0 !important;
}
footer { display: none !important; }
.gr-form { background: transparent !important; border: none !important; }

.hero {
    background: linear-gradient(180deg, #0a0a12 0%, #030305 100%);
    padding: 60px 20px 40px;
    text-align: center;
    border-bottom: 1px solid #1a1a2e;
}
.hero-badge {
    display: inline-block;
    background: #8B5CF620;
    border: 1px solid #8B5CF640;
    color: #8B5CF6;
    padding: 6px 16px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    letter-spacing: 0.1em;
    text-transform: uppercase;
    margin-bottom: 20px;
}
.hero-logo {
    width: 70px;
    height: 70px;
    border-radius: 16px;
    margin: 0 auto 20px;
    background: linear-gradient(135deg, #8B5CF6 0%, #6D28D9 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 0 40px #8B5CF650;
}
.hero-logo img { width: 50px; height: 50px; }
.hero-title {
    font-size: 42px;
    font-weight: 900;
    color: #fff;
    letter-spacing: 0.15em;
    margin: 0 0 12px 0;
    text-shadow: 0 0 30px #8B5CF640;
}
.hero-subtitle {
    color: #9CA3AF;
    font-size: 18px;
    font-weight: 500;
    margin: 0 0 20px 0;
    letter-spacing: 0.02em;
}
.hero-desc {
    color: #9CA3AF;
    font-size: 15px;
    max-width: 700px;
    margin: 0 auto 30px;
    line-height: 1.7;
}
.hero-emphasis {
    color: #8B5CF6;
    font-weight: 600;
}
.hero-stats {
    display: flex;
    justify-content: center;
    gap: 40px;
    margin: 30px auto 0;
    max-width: 900px;
    flex-wrap: wrap;
}
.stat-item {
    text-align: center;
}
.stat-label {
    color: #6B7280;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.1em;
    font-weight: 600;
}
.stat-value {
    color: #fff;
    font-size: 16px;
    font-weight: 700;
    margin-top: 4px;
}
.stat-link {
    color: #8B5CF6;
    text-decoration: none;
    font-size: 16px;
    font-weight: 700;
}
.stat-link:hover {
    color: #A78BFA;
}

.nav {
    display: flex;
    justify-content: center;
    gap: 24px;
    padding: 16px;
    background: #050507;
    border-bottom: 1px solid #1a1a2e;
    flex-wrap: wrap;
}
.nav a {
    color: #9CA3AF;
    text-decoration: none;
    font-size: 13px;
    font-weight: 500;
    transition: color 0.2s;
}
.nav a:hover { color: #8B5CF6; }

.search-section {
    max-width: 700px;
    margin: 40px auto;
    padding: 0 20px;
}
.search-box {
    display: flex;
    gap: 12px;
}
input[type="text"], textarea {
    flex: 1;
    background: #0a0a12 !important;
    border: 2px solid #1a1a2e !important;
    color: #fff !important;
    border-radius: 12px !important;
    padding: 16px 20px !important;
    font-size: 16px !important;
}
input:focus, textarea:focus {
    border-color: #8B5CF6 !important;
    box-shadow: 0 0 20px #8B5CF620 !important;
    outline: none !important;
}
button.primary {
    background: linear-gradient(135deg, #8B5CF6 0%, #6D28D9 100%) !important;
    border: none !important;
    padding: 16px 32px !important;
    border-radius: 12px !important;
    font-weight: 700 !important;
    font-size: 14px !important;
    letter-spacing: 0.05em !important;
    color: #fff !important;
    cursor: pointer !important;
    transition: all 0.2s;
}
button.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 30px #8B5CF650 !important;
}

.error-box { background: #1a0a0a; border: 1px solid #EF4444; border-radius: 12px; padding: 20px; color: #EF4444; text-align: center; }

.stats-section {
    max-width: 1200px;
    margin: 40px auto;
    padding: 0 20px;
}
.stats-box {
    background: #0a0a12;
    border: 1px solid #1a1a2e;
    border-radius: 16px;
    padding: 30px;
    margin-bottom: 20px;
}
.stats-title {
    color: #8B5CF6;
    font-size: 14px;
    font-weight: 700;
    letter-spacing: 0.1em;
    text-transform: uppercase;
    margin-bottom: 20px;
    text-align: center;
}
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}
.stat-item {
    text-align: center;
}
.stat-value {
    color: #fff;
    font-size: 32px;
    font-weight: 900;
    margin-bottom: 8px;
}
.stat-label {
    color: #6B7280;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.1em;
}
.stats-footer {
    color: #4B5563;
    font-size: 11px;
    text-align: center;
    padding-top: 20px;
    border-top: 1px solid #1a1a2e;
    font-family: monospace;
}

.merkle-box {
    background: #0a0a12;
    border: 1px solid #1a1a2e;
    border-radius: 16px;
    padding: 30px;
    margin-bottom: 20px;
}
.merkle-title {
    color: #8B5CF6;
    font-size: 14px;
    font-weight: 700;
    letter-spacing: 0.1em;
    text-transform: uppercase;
    margin-bottom: 20px;
    text-align: center;
}
.merkle-hash {
    background: #050507;
    border: 1px solid #1a1a2e;
    border-radius: 8px;
    padding: 16px;
    color: #22C55E;
    font-family: monospace;
    font-size: 13px;
    word-break: break-all;
    margin-bottom: 16px;
    text-align: center;
}
.merkle-meta {
    color: #6B7280;
    font-size: 12px;
    text-align: center;
    line-height: 1.8;
}

.merkle-timeline-box {
    background: #0a0a12;
    border: 1px solid #1a1a2e;
    border-radius: 16px;
    padding: 30px;
    margin-bottom: 20px;
}
.timeline-entries {
    max-height: 400px;
    overflow-y: auto;
}
.timeline-entry {
    background: #050507;
    border: 1px solid #1a1a2e;
    border-radius: 8px;
    padding: 12px 16px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
}
.timeline-time {
    color: #9CA3AF;
    font-size: 11px;
    font-family: monospace;
    min-width: 150px;
}
.timeline-hash {
    color: #22C55E;
    font-size: 11px;
    font-family: monospace;
    flex: 1;
}
.timeline-obs {
    color: #6B7280;
    font-size: 11px;
    min-width: 120px;
    text-align: right;
}

.anchor-box {
    background: #0a0a12;
    border: 1px solid #1a1a2e;
    border-radius: 16px;
    padding: 30px;
    margin-bottom: 20px;
}
.anchor-title {
    color: #8B5CF6;
    font-size: 14px;
    font-weight: 700;
    letter-spacing: 0.1em;
    text-transform: uppercase;
    margin-bottom: 20px;
    text-align: center;
}
.anchor-section {
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #1a1a2e;
}
.anchor-section:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}
.anchor-label {
    color: #8B5CF6;
    font-size: 11px;
    font-weight: 600;
    letter-spacing: 0.05em;
    text-transform: uppercase;
    margin-bottom: 8px;
}
.anchor-value {
    color: #9CA3AF;
    font-size: 13px;
    line-height: 1.8;
    font-family: monospace;
}
.anchor-link {
    color: #8B5CF6;
    text-decoration: none;
    word-break: break-all;
}
.anchor-link:hover {
    color: #A78BFA;
    text-decoration: underline;
}

.observations-section {
    background: #050507;
    padding: 40px 20px;
    border-top: 1px solid #1a1a2e;
}
.observations-title {
    text-align: center;
    color: #fff;
    font-size: 24px;
    font-weight: 700;
    margin-bottom: 8px;
}
.observations-sub {
    text-align: center;
    color: #6B7280;
    font-size: 13px;
    margin-bottom: 30px;
}
.observations-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 16px;
    max-width: 1200px;
    margin: 0 auto;
}
.observation-card {
    background: #0a0a12;
    border: 1px solid #1a1a2e;
    border-radius: 12px;
    padding: 20px;
    transition: transform 0.2s, box-shadow 0.2s;
}
.observation-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 10px 30px rgba(139, 92, 246, 0.15);
    border-color: #8B5CF640;
}
.obs-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}
.obs-type {
    background: #8B5CF620;
    color: #8B5CF6;
    padding: 4px 12px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 0.05em;
}
.obs-timestamp {
    color: #6B7280;
    font-size: 11px;
    font-family: monospace;
}
.obs-target {
    color: #fff;
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 4px;
    word-break: break-all;
}
.obs-days {
    color: #8B5CF6;
    font-size: 11px;
    font-weight: 600;
    margin-bottom: 8px;
    letter-spacing: 0.05em;
}
.obs-meta {
    color: #6B7280;
    font-size: 12px;
}

.site-footer {
    background: #030305;
    border-top: 1px solid #1a1a2e;
    padding: 40px 20px 30px;
    text-align: center;
}
.footer-tagline {
    color: #8B5CF6;
    font-size: 14px;
    font-weight: 600;
    margin-bottom: 20px;
    letter-spacing: 0.05em;
}
.footer-links { display: flex; justify-content: center; gap: 24px; margin-bottom: 20px; flex-wrap: wrap; }
.footer-links a { color: #6B7280; text-decoration: none; font-size: 13px; }
.footer-links a:hover { color: #8B5CF6; }
.footer-copy { color: #4B5563; font-size: 11px; margin-bottom: 8px; }
.footer-protocol { color: #374151; font-size: 10px; font-family: monospace; }

.cta-panel {
    background: linear-gradient(180deg, rgba(139,92,246,0.16) 0%, rgba(3,3,5,0.0) 100%);
    border: 1px solid rgba(139,92,246,0.35);
    border-radius: 16px;
    padding: 18px 18px 14px;
    margin: 16px auto 18px;
    max-width: 1180px;
}
.cta-title {
    color: #EDE9FE;
    font-weight: 800;
    letter-spacing: 0.06em;
    font-size: 12px;
    text-transform: uppercase;
    margin: 0 0 8px;
}
.cta-desc {
    color: #A1A1AA;
    font-size: 13px;
    margin: 0 0 12px;
}
.cta-hint {
    color: #9CA3AF;
    font-size: 12px;
    margin: 10px 0 0;
}
.cta-status {
    color: #C4B5FD;
    font-size: 12px;
    margin: 8px 0 0;
}

/* Gradio dark theme overrides */
.gradio-container { background: transparent !important; }
.gradio-container * { color-scheme: dark; }
.gradio-container .markdown,
.gradio-container .markdown p,
.gradio-container .prose,
.gradio-container .prose p,
.gradio-container .md,
.gradio-container .md p {
    color: #E5E7EB !important;
}
.gradio-container a { color: #A78BFA !important; }
.gradio-container a:hover { color: #C4B5FD !important; }
.gradio-container input,
.gradio-container textarea,
.gradio-container select,
.gradio-container pre,
.gradio-container code {
    background: #0a0a12 !important;
    color: #E5E7EB !important;
    border: 1px solid #1a1a2e !important;
}
.gradio-container label,
.gradio-container .label {
    color: #9CA3AF !important;
}
.gradio-container .block,
.gradio-container .gr-box,
.gradio-container .form,
.gradio-container .wrap,
.gradio-container .panel,
.gradio-container .gr-panel {
    background: #050507 !important;
    border-color: #1a1a2e !important;
}
.gradio-container button {
    border: 1px solid #1a1a2e !important;
}

@media (max-width: 640px) {
    .hero-title { font-size: 32px; }
    .hero-subtitle { font-size: 16px; }
    .hero-stats { gap: 20px; }
    .nav { gap: 16px; }
    .search-box { flex-direction: column; }
    button.primary { width: 100%; }
    .cards-grid { grid-template-columns: 1fr; }
}

"""

HEADER_HTML = f'''
<div class="hero">
    <div class="hero-badge">� OPERATIONAL · PROTOCOL {PROTOCOL_VERSION}</div>
    <div class="hero-logo">
        <img src="https://huggingface.co/spaces/Crovia/omission-oracle/resolve/main/crovia-logo.png" alt="Crovia" onerror="this.style.display='none'">
    </div>
    <h1 class="hero-title">CROVIA</h1>
    <p class="hero-subtitle">Training Provenance Registry Observer</p>
    <p class="hero-desc">
        Public evidence viewer. <span class="hero-emphasis">Observation, not judgment.</span>
        Displays verifiable data from TPR Registry: observations, stats, merkle roots.
    </p>
    <div class="hero-stats">
        <div class="stat-item">
            <div class="stat-label">Protocol</div>
            <div class="stat-value">{PROTOCOL_VERSION} · Feb 2026</div>
        </div>
        <div class="stat-item">
            <div class="stat-label">Registry</div>
            <a href="https://registry.croviatrust.com" target="_blank" class="stat-link">
                Live API →
            </a>
        </div>
        <div class="stat-item">
            <div class="stat-label">Open Source</div>
            <a href="https://github.com/croviatrust" target="_blank" class="stat-link">
                GitHub →
            </a>
        </div>
    </div>
</div>
<div class="nav">
    <a href="https://croviatrust.com" target="_blank">Home</a>
    <a href="https://registry.croviatrust.com/registry" target="_blank">Registry</a>
    <a href="https://registry.croviatrust.com/registry/omissions" target="_blank">Omissions</a>
    <a href="https://registry.croviatrust.com/registry/tpa" target="_blank" style="color:#f59e0b !important;font-weight:700;">TPA</a>
    <a href="https://registry.croviatrust.com/registry/outreach" target="_blank" style="color:#10b981 !important;font-weight:700;">Outreach & Impact</a>
    <a href="https://registry.croviatrust.com/registry/compliance" target="_blank" style="color:#3b82f6 !important;font-weight:700;">Compliance</a>
    <a href="https://registry.croviatrust.com/registry/lineage/" target="_blank">Lineage</a>
    <a href="https://github.com/croviatrust" target="_blank">GitHub</a>
</div>
'''

def generate_observations_html() -> str:
    return '''
<div style="margin-top:24px;">
    <div style="background:#12121a;border:1px solid #1e1e2e;border-radius:14px;overflow:hidden;">
        <iframe src="https://registry.croviatrust.com/registry/lineage/"
                style="width:100%;height:820px;border:none;background:#0a0a0f;"
                loading="lazy"
                sandbox="allow-scripts allow-same-origin"
                title="Disclosure Lineage Graph">
        </iframe>
    </div>
</div>
'''

FOOTER_HTML = '''
<div class="site-footer">
    <div class="footer-tagline">We observe. We record. We do not judge.</div>
    <div class="footer-links">
        <a href="https://croviatrust.com">Official Site</a>
        <a href="https://registry.croviatrust.com/registry">Registry</a>
        <a href="https://github.com/croviatrust">GitHub</a>
        <a href="https://huggingface.co/datasets/Crovia/global-ai-training-omissions">Dataset</a>
    </div>
    <p class="footer-copy">&copy; 2026 CroviaTrust. Training Provenance Registry.</p>
    <p class="footer-protocol">Protocol v1.1 &middot; Evidence-first, judgment-free.</p>
</div>
'''

_TARGET_CHOICES_CACHE: Optional[Tuple[List[str], List[str]]] = None


def _load_target_choices() -> Tuple[List[str], List[str]]:
    global _TARGET_CHOICES_CACHE
    if _TARGET_CHOICES_CACHE is not None:
        return _TARGET_CHOICES_CACHE
    try:
        r = requests.get(f"{TPR_API_URL}/api/targets/summary", timeout=5)
        if r.status_code != 200:
            return ([], [])
        targets = r.json().get('targets', []) or []
        models = sorted({t.get('target_id') for t in targets if t.get('tipo_target') == 'model' and t.get('target_id')})
        datasets = sorted({t.get('target_id') for t in targets if t.get('tipo_target') == 'dataset' and t.get('target_id')})
        # Only cache non-empty results, so a transient outage doesn't "stick" forever.
        if models or datasets:
            _TARGET_CHOICES_CACHE = (models, datasets)
        return (models, datasets)
    except Exception:
        return ([], [])


def _infer_tipo_target(target_id: str) -> str:
    try:
        r = requests.get(f"{TPR_API_URL}/api/targets/summary", timeout=5)
        if r.status_code != 200:
            return 'unknown'
        targets = r.json().get('targets', []) or []
        t = next((x for x in targets if x.get('target_id') == target_id), None)
        return (t.get('tipo_target') if isinstance(t, dict) else None) or 'unknown'
    except Exception:
        return 'unknown'


def _hf_api_url(tipo_target: str, target_id: str) -> Optional[str]:
    if tipo_target == 'model':
        return f"https://huggingface.co/api/models/{target_id}"
    if tipo_target == 'dataset':
        return f"https://huggingface.co/api/datasets/{target_id}"
    return None


def _hf_readme_url(tipo_target: str, target_id: str) -> Optional[str]:
    if tipo_target == 'model':
        return f"https://huggingface.co/{target_id}/raw/main/README.md"
    if tipo_target == 'dataset':
        return f"https://huggingface.co/datasets/{target_id}/raw/main/README.md"
    return None


def _fetch_text(url: str) -> Tuple[Optional[str], Dict[str, Any]]:
    meta: Dict[str, Any] = {"url": url}
    try:
        r = requests.get(url, timeout=15)
        meta["http_status"] = r.status_code
        meta["fetched_at"] = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
        if r.status_code != 200:
            meta["error"] = f"HTTP {r.status_code}"
            return None, meta
        return r.text, meta
    except Exception as e:
        meta["error"] = f"{type(e).__name__}: {e}"
        return None, meta


def _fetch_json(url: str) -> Tuple[Optional[Dict[str, Any]], Dict[str, Any]]:
    meta: Dict[str, Any] = {"url": url}
    try:
        r = requests.get(url, timeout=15)
        meta["http_status"] = r.status_code
        meta["fetched_at"] = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
        if r.status_code != 200:
            meta["error"] = f"HTTP {r.status_code}"
            return None, meta
        return r.json(), meta
    except Exception as e:
        meta["error"] = f"{type(e).__name__}: {e}"
        return None, meta


def _sha256_hex(s: str) -> str:
    return hashlib.sha256(s.encode('utf-8', errors='replace')).hexdigest()


def generate_disclosure_fingerprint(target_id: str) -> str:
    if not target_id:
        return json.dumps({"error": "missing target_id"}, indent=2)

    tipo = _infer_tipo_target(target_id)
    api_url = _hf_api_url(tipo, target_id)
    readme_url = _hf_readme_url(tipo, target_id)

    api_json: Optional[Dict[str, Any]] = None
    api_meta: Dict[str, Any] = {}
    if api_url:
        api_json, api_meta = _fetch_json(api_url)

    readme_text: Optional[str] = None
    readme_meta: Dict[str, Any] = {}
    if readme_url:
        readme_text, readme_meta = _fetch_text(readme_url)

    readme_access = "unknown"
    try:
        status = int(readme_meta.get('http_status')) if readme_meta.get('http_status') is not None else None
        if status == 200:
            readme_access = "ok"
        elif status == 401 or status == 403:
            readme_access = "forbidden"
        elif status == 404:
            readme_access = "not_found"
        elif status is not None:
            readme_access = "error"
    except Exception:
        readme_access = "error"

    card_data = (api_json.get('cardData') if isinstance(api_json, dict) else None) or {}
    license_val = card_data.get('license') if isinstance(card_data, dict) else None
    datasets_declared = card_data.get('datasets') if isinstance(card_data, dict) else None
    tags_val = api_json.get('tags') if isinstance(api_json, dict) else None
    lang_val = card_data.get('language') if isinstance(card_data, dict) else None

    tags_list: List[str] = []
    if isinstance(tags_val, list):
        tags_list = [str(x) for x in tags_val if x is not None]
    elif isinstance(tags_val, str):
        tags_list = [tags_val]

    lang_list: List[str] = []
    if isinstance(lang_val, list):
        lang_list = [str(x) for x in lang_val if x is not None]
    elif isinstance(lang_val, str):
        lang_list = [lang_val]

    has_training_section = False
    if readme_text:
        has_training_section = bool(re.search(r"^##\s+training\b", readme_text, flags=re.IGNORECASE | re.MULTILINE))

    card_canonical = json.dumps(card_data, sort_keys=True, separators=(',', ':'), ensure_ascii=True)
    card_hash = _sha256_hex(card_canonical)
    readme_hash = _sha256_hex(readme_text) if readme_text else None

    extracted = {
        "license": license_val,
        "declared_datasets": datasets_declared,
        "tags_count": len(tags_list),
        "tags_sample": tags_list[:25],
        "tags_hash": _sha256_hex(json.dumps(tags_list, sort_keys=True, separators=(',', ':'), ensure_ascii=True)),
        "language_count": len(lang_list),
        "language_sample": lang_list[:25],
        "language_hash": _sha256_hex(json.dumps(lang_list, sort_keys=True, separators=(',', ':'), ensure_ascii=True)),
        "has_training_section": has_training_section,
        "readme_access": readme_access,
    }

    ddf = {
        "schema": "crovia.open.ddf_preview.v1",
        "target_id": target_id,
        "tipo_target": tipo,
        "observed_at": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
        "sources": {
            "registry": f"{TPR_API_URL}/api/targets/summary",
            "hf_api": api_meta,
            "hf_readme": readme_meta,
        },
        "extracted": extracted,
        "hashes": {
            "card_hash": card_hash,
            "readme_hash": readme_hash,
        },
    }

    ddf_canonical = json.dumps(ddf, sort_keys=True, separators=(',', ':'), ensure_ascii=True)
    ddf["hashes"]["ddf_hash"] = _sha256_hex(ddf_canonical)

    return json.dumps(ddf, indent=2, ensure_ascii=False)


def linkage_probe(model_id: str, dataset_id: str) -> str:
    if not model_id or not dataset_id:
        return json.dumps({"error": "missing model_id or dataset_id"}, indent=2)

    model_api_url = _hf_api_url('model', model_id)
    model_readme_url = _hf_readme_url('model', model_id)

    api_json, api_meta = _fetch_json(model_api_url) if model_api_url else (None, {})
    readme_text, readme_meta = _fetch_text(model_readme_url) if model_readme_url else (None, {})

    readme_access = "unknown"
    try:
        status = int(readme_meta.get('http_status')) if readme_meta.get('http_status') is not None else None
        if status == 200:
            readme_access = "ok"
        elif status == 401 or status == 403:
            readme_access = "forbidden"
        elif status == 404:
            readme_access = "not_found"
        elif status is not None:
            readme_access = "error"
    except Exception:
        readme_access = "error"

    card_data = (api_json.get('cardData') if isinstance(api_json, dict) else None) or {}
    declared = card_data.get('datasets') if isinstance(card_data, dict) else None

    declared_list: List[str] = []
    if isinstance(declared, list):
        declared_list = [str(x) for x in declared if x is not None]
    elif isinstance(declared, str):
        declared_list = [declared]

    declared_hit = any(x.strip().lower() == dataset_id.strip().lower() for x in declared_list)

    mention_hit = False
    mention_evidence: List[str] = []
    if readme_text:
        low = readme_text.lower()
        ds = dataset_id.lower()
        if ds in low:
            mention_hit = True
            mention_evidence.append("readme_text:dataset_id")
        ds_short = dataset_id.split('/')[-1].lower()
        if ds_short and ds_short in low and ds_short != ds:
            mention_hit = True
            mention_evidence.append("readme_text:dataset_slug")
        if f"huggingface.co/datasets/{ds}" in low:
            mention_hit = True
            mention_evidence.append("readme_text:hf_dataset_url")

    status = "not_observed"
    support = "none"
    if declared_hit:
        status = "declared"
        support = "strong"
    elif mention_hit:
        status = "mention"
        support = "weak"

    out = {
        "schema": "crovia.open.linkage_probe.v1",
        "model_id": model_id,
        "dataset_id": dataset_id,
        "observed_at": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
        "status": status,
        "support": support,
        "coverage": {
            "readme_access": readme_access,
        },
        "evidence": {
            "hf_model_api": api_meta,
            "hf_model_readme": readme_meta,
            "declared_datasets": declared_list,
            "mention_evidence": mention_evidence,
        },
        "hashes": {
            "model_card_hash": _sha256_hex(json.dumps(card_data, sort_keys=True, separators=(',', ':'), ensure_ascii=True)),
            "model_readme_hash": _sha256_hex(readme_text) if readme_text else None,
        },
        "note": "This does not establish usage. It only reports whether a public linkage was observed.",
    }

    out_canonical = json.dumps(out, sort_keys=True, separators=(',', ':'), ensure_ascii=True)
    out["hashes"]["probe_hash"] = _sha256_hex(out_canonical)
    return json.dumps(out, indent=2, ensure_ascii=False)

_OUTREACH_CACHE: Dict[str, Any] = {"ts": 0.0, "items": []}
_OUTREACH_TTL_SEC = 600  # 10 min

# --- Dynamic peer comparison from lineage graph (cached) ---
_PEER_CACHE: Dict[str, Any] = {"ts": 0.0, "data": None}
_PEER_TTL_SEC = 600  # 10 min

def _load_peer_comparison() -> Dict[str, Any]:
    """Fetch peer comparison metrics from live lineage graph. Cached 10 min."""
    import time as _t
    now = _t.time()
    if now - _PEER_CACHE["ts"] < _PEER_TTL_SEC and _PEER_CACHE["data"]:
        return _PEER_CACHE["data"]
    fallback = {"doc_rate": 83.5, "total_models": 141, "total_orgs": 70, "generated_at": "unknown"}
    try:
        r = requests.get("https://registry.croviatrust.com/registry/data/lineage_graph.json", timeout=10)
        if r.status_code == 200:
            d = r.json()
            metrics = d.get("metrics", {})
            nodes = d.get("nodes", [])
            models = [n for n in nodes if n.get("type") == "model"]
            shadows = [n for n in nodes if n.get("type") == "shadow"]
            orgs = [n for n in nodes if n.get("type") == "org"]
            total = len(models) + len(shadows)
            doc_rate = round((len(models) / total * 100), 1) if total > 0 else 0.0
            result = {
                "doc_rate": doc_rate,
                "total_models": total,
                "total_orgs": len(orgs),
                "generated_at": d.get("generated_at", "unknown"),
            }
            _PEER_CACHE["ts"] = now
            _PEER_CACHE["data"] = result
            return result
    except Exception:
        pass
    return _PEER_CACHE["data"] or fallback

# --- Public organization revenue (from SEC filings, cited) ---
_ORG_PUBLIC_REVENUE = {
    "google":    {"legal": "Alphabet Inc.",              "usd": "$307.4B", "src": "Form 10-K, FY2023, SEC EDGAR"},
    "google-bert":{"legal": "Alphabet Inc.",             "usd": "$307.4B", "src": "Form 10-K, FY2023, SEC EDGAR"},
    "google-t5": {"legal": "Alphabet Inc.",              "usd": "$307.4B", "src": "Form 10-K, FY2023, SEC EDGAR"},
    "meta-llama":{"legal": "Meta Platforms, Inc.",       "usd": "$134.9B", "src": "Form 10-K, FY2023, SEC EDGAR"},
    "facebook":  {"legal": "Meta Platforms, Inc.",       "usd": "$134.9B", "src": "Form 10-K, FY2023, SEC EDGAR"},
    "FacebookAI":{"legal": "Meta Platforms, Inc.",       "usd": "$134.9B", "src": "Form 10-K, FY2023, SEC EDGAR"},
    "microsoft": {"legal": "Microsoft Corporation",     "usd": "$211.9B", "src": "Form 10-K, FY2023, SEC EDGAR"},
    "nvidia":    {"legal": "NVIDIA Corporation",         "usd": "$60.9B",  "src": "Form 10-K, FY2024, SEC EDGAR"},
    "amazon":    {"legal": "Amazon.com, Inc.",           "usd": "$574.8B", "src": "Form 10-K, FY2023, SEC EDGAR"},
    "Salesforce":{"legal": "Salesforce, Inc.",           "usd": "$34.9B",  "src": "Form 10-K, FY2024, SEC EDGAR"},
    "ibm-granite":{"legal":"IBM Corporation",            "usd": "$61.9B",  "src": "Form 10-K, FY2023, SEC EDGAR"},
    "Qwen":      {"legal": "Alibaba Group",             "usd": "$125.7B", "src": "Form 20-F, FY2024, SEC EDGAR"},
    "OpenGVLab": {"legal": "Shanghai AI Laboratory",    "usd": None,      "src": None},
}

# --- Published regulation citations (verbatim article text) ---
_REGULATIONS = [
    {
        "name": "EU AI Act",
        "reg":  "Regulation (EU) 2024/1689",
        "art":  "Art. 101(1)",
        "text": "up to EUR 15,000,000 or, if the offender is an undertaking, up to 3% of its total worldwide annual turnover for the preceding financial year, whichever is higher",
        "scope": "Obligations for providers of general-purpose AI models (Art. 53)",
        "src":  "Official Journal of the European Union, L series, 12 July 2024",
        "nec":  ["NEC#1", "NEC#2", "NEC#7", "NEC#10", "NEC#13"],
    },
    {
        "name": "EU GDPR",
        "reg":  "Regulation (EU) 2016/679",
        "art":  "Art. 83(5)",
        "text": "up to EUR 20,000,000 or, in the case of an undertaking, up to 4% of the total worldwide annual turnover of the preceding financial year, whichever is higher",
        "scope": "Infringements of basic principles for processing, including data provenance",
        "src":  "Official Journal of the European Union, L 119, 4 May 2016",
        "nec":  ["NEC#1", "NEC#2"],
    },
]

def _load_outreach_data() -> List[Dict[str, Any]]:
    """Load per-model outreach data from HF dataset (sent_discussions.jsonl)."""
    import time as _t
    now = _t.time()
    if now - _OUTREACH_CACHE["ts"] < _OUTREACH_TTL_SEC and _OUTREACH_CACHE["items"]:
        return _OUTREACH_CACHE["items"]
    try:
        url = "https://huggingface.co/datasets/Crovia/global-ai-training-omissions/resolve/main/sent_discussions.jsonl"
        r = requests.get(url, timeout=15)
        if r.status_code == 200:
            entries = []
            for line in r.text.strip().split('\n'):
                if line.strip():
                    entries.append(json.loads(line))
            _OUTREACH_CACHE["ts"] = now
            _OUTREACH_CACHE["items"] = entries
            return entries
    except Exception:
        pass
    return _OUTREACH_CACHE["items"] or []


def _get_target_tpa(target_id: str) -> Optional[Dict[str, Any]]:
    """Find TPA data for a specific target."""
    tpa_data = _load_tpa_latest()
    if not tpa_data or not tpa_data.get('tpas'):
        return None
    for tpa in tpa_data['tpas']:
        if tpa.get('model_id') == target_id:
            return tpa
    return None


def generate_model_lookup_html(target_id: str) -> str:
    """Generate comprehensive evidence profile HTML for a single target."""
    if not target_id:
        return '<div style="color:#71717a;text-align:center;padding:40px;">Select a target from the dropdown above.</div>'

    # --- 1. Registry data ---
    reg_data = None
    try:
        r = requests.get(f"{TPR_API_URL}/api/targets/summary", timeout=5)
        if r.status_code == 200:
            targets = r.json().get('targets', [])
            reg_data = next((t for t in targets if t.get('target_id') == target_id), None)
    except Exception:
        pass

    if not reg_data:
        days = 0; obs_count = 0; streak = 0
        first_seen = "Not yet observed"; last_seen = "\u2014"
        not_in_registry = True
    else:
        days = int(reg_data.get('days_monitored', 0) or 0)
        obs_count = int(reg_data.get('observation_count', 0) or 0)
        streak = int(reg_data.get('absence_streak_days', 0) or 0)
        first_seen = (reg_data.get('first_seen') or '')[:19] or "\u2014"
        last_seen = (reg_data.get('last_seen') or '')[:19] or "\u2014"
        not_in_registry = False

    # --- 2. TPA data ---
    tpa = _get_target_tpa(target_id)
    tpa_html = ""
    nec_html = ""
    jurisdictions_count = 0
    gaps_count = 0

    if tpa:
        obs = tpa.get('observations', [])
        absent = [o for o in obs if not o.get('is_present')]
        present = [o for o in obs if o.get('is_present')]
        jurs = tpa.get('jurisdiction_exposures', [])
        jurisdictions_count = tpa.get('total_jurisdictions_exposed', len(jurs))
        gaps_count = len(absent)
        merkle = tpa.get('merkle_root', '')[:24]
        tpa_id = tpa.get('tpa_id', '\u2014')

        nec_rows = ""
        for o in sorted(obs, key=lambda x: x.get('necessity_id', '')):
            nec_id = o.get('necessity_id', '')
            nec_name = o.get('necessity_name', '')
            is_present = o.get('is_present', False)
            bar_color = "#22c55e" if is_present else "#ef4444"
            bar_bg = "#22c55e15" if is_present else "#ef444415"
            status_text = "DOCUMENTED" if is_present else "NOT DOCUMENTED"
            nec_rows += f'''<div style="display:flex;align-items:center;justify-content:space-between;padding:10px 16px;background:{bar_bg};border-left:3px solid {bar_color};border-radius:0 8px 8px 0;margin-bottom:6px;">
                <div><span style="color:#fff;font-weight:700;font-family:monospace;font-size:13px;">{nec_id}</span><span style="color:#a1a1aa;font-size:12px;margin-left:8px;">{nec_name}</span></div>
                <span style="color:{bar_color};font-weight:700;font-size:11px;letter-spacing:0.05em;">{status_text}</span>
            </div>'''

        nec_html = f'''<div style="margin-top:24px;">
            <div style="color:#a78bfa;font-weight:700;font-size:13px;letter-spacing:0.08em;margin-bottom:12px;">DOCUMENTATION GAPS OBSERVED</div>
            {nec_rows}
            <div style="color:#71717a;font-size:11px;font-style:italic;margin-top:8px;">Based on model card analysis at time of observation.</div>
        </div>'''

        tpa_html = f'''<div style="margin-top:24px;background:#0f0f1a;border:1px solid #1a1a2e;border-radius:12px;padding:16px;">
            <div style="color:#f59e0b;font-weight:700;font-size:13px;letter-spacing:0.08em;margin-bottom:12px;">TEMPORAL PROOF OF ABSENCE</div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;font-size:12px;">
                <div><span style="color:#71717a;">TPA ID:</span> <span style="color:#fff;font-family:monospace;">{tpa_id}</span></div>
                <div><span style="color:#71717a;">Verification:</span> <span style="color:#22c55e;font-weight:700;">26/26 checks</span></div>
                <div><span style="color:#71717a;">Merkle:</span> <span style="color:#22c55e;font-family:monospace;">{merkle}...</span></div>
                <div><span style="color:#71717a;">Crypto:</span> <span style="color:#a1a1aa;">Pedersen secp256k1 &middot; Ed25519</span></div>
            </div>
        </div>'''

        if jurs:
            jur_tags = ' '.join(
                f'<span style="padding:3px 8px;background:#8B5CF610;border:1px solid #8B5CF644;border-radius:5px;font-size:10px;color:#A78BFA;">{j.get("jurisdiction_name","")}</span>'
                for j in jurs
            )
            tpa_html += f'''<div style="margin-top:12px;">
                <div style="color:#71717a;font-size:10px;text-transform:uppercase;letter-spacing:1px;margin-bottom:8px;">Jurisdictions Exposed ({jurisdictions_count})</div>
                <div style="display:flex;flex-wrap:wrap;gap:6px;">{jur_tags}</div>
            </div>'''

    # --- 2b. NEC# fallback when no TPA: real-time HF metadata check ---
    if not tpa and not not_in_registry:
        tipo = _infer_tipo_target(target_id)
        api_url = _hf_api_url(tipo, target_id)
        readme_url = _hf_readme_url(tipo, target_id)
        hf_api_json = None
        hf_readme_text = None
        try:
            if api_url:
                hf_api_json, _ = _fetch_json(api_url)
            if readme_url:
                hf_readme_text, _ = _fetch_text(readme_url)
        except Exception:
            pass

        card_d = (hf_api_json.get('cardData') if isinstance(hf_api_json, dict) else None) or {}
        license_val = card_d.get('license') if isinstance(card_d, dict) else None
        datasets_declared = card_d.get('datasets') if isinstance(card_d, dict) else None
        has_training = bool(hf_readme_text and re.search(r'(?i)##\s+training', hf_readme_text))
        has_usage = bool(hf_readme_text and re.search(r'(?i)##\s+(intended\s+)?use', hf_readme_text))
        has_temporal = bool(card_d.get('created_at') or (hf_readme_text and re.search(r'(?i)(version|date|release)', hf_readme_text)))
        has_entity = bool(hf_api_json.get('author') if isinstance(hf_api_json, dict) else False)

        nec_checks = [
            ("NEC#1", "Data Provenance", bool(datasets_declared) or has_training),
            ("NEC#2", "License Attribution", bool(license_val)),
            ("NEC#7", "Usage Scope", has_usage),
            ("NEC#10", "Temporal Validity", has_temporal),
            ("NEC#13", "Accountable Entity", has_entity),
        ]
        gaps_count = sum(1 for _, _, present in nec_checks if not present)

        nec_rows = ""
        for nec_id, nec_name, is_present in nec_checks:
            bar_color = "#22c55e" if is_present else "#ef4444"
            bar_bg = "#22c55e15" if is_present else "#ef444415"
            status_text = "DOCUMENTED" if is_present else "NOT DOCUMENTED"
            nec_rows += f'''<div style="display:flex;align-items:center;justify-content:space-between;padding:10px 16px;background:{bar_bg};border-left:3px solid {bar_color};border-radius:0 8px 8px 0;margin-bottom:6px;">
                <div><span style="color:#fff;font-weight:700;font-family:monospace;font-size:13px;">{nec_id}</span><span style="color:#a1a1aa;font-size:12px;margin-left:8px;">{nec_name}</span></div>
                <span style="color:{bar_color};font-weight:700;font-size:11px;letter-spacing:0.05em;">{status_text}</span>
            </div>'''

        nec_html = f'''<div style="margin-top:24px;">
            <div style="color:#a78bfa;font-weight:700;font-size:13px;letter-spacing:0.08em;margin-bottom:12px;">DOCUMENTATION GAPS OBSERVED</div>
            {nec_rows}
            <div style="color:#71717a;font-size:11px;font-style:italic;margin-top:8px;">Real-time check from public HuggingFace metadata. No TPA generated yet for this target.</div>
        </div>'''

    # --- 3. Outreach data ---
    outreach_html = ""
    try:
        entries = _load_outreach_data()
        if isinstance(entries, list):
            entry = next((e for e in entries if e.get('repo_id') == target_id or e.get('target_id') == target_id or e.get('model_id') == target_id), None)
            if entry:
                status = entry.get('status', 'unknown')
                disc_url = entry.get('discussion_url', '')
                sent_date = (entry.get('sent_at') or entry.get('created_at') or '')[:10]
                status_color = "#f59e0b" if status == "pending" else "#22c55e" if status in ("responded","acknowledged") else "#ef4444" if status == "closed" else "#71717a"
                disc_link = f'<a href="{disc_url}" target="_blank" style="color:#8B5CF6 !important;text-decoration:none;font-size:12px;">View discussion &rarr;</a>' if disc_url else ''
                outreach_html = f'''<div style="margin-top:24px;background:#0f0f1a;border:1px solid #1a1a2e;border-radius:12px;padding:16px;">
                    <div style="color:#10b981;font-weight:700;font-size:13px;letter-spacing:0.08em;margin-bottom:12px;">OUTREACH</div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;font-size:12px;">
                        <div><span style="color:#71717a;">Discussion sent:</span> <span style="color:#fff;">{sent_date}</span></div>
                        <div><span style="color:#71717a;">Status:</span> <span style="color:{status_color};font-weight:700;text-transform:uppercase;">{status}</span></div>
                    </div>
                    <div style="margin-top:8px;">{disc_link}</div>
                </div>'''
    except Exception:
        pass

    # --- 4. Stats cards ---
    freq = f"{obs_count/max(days,1):.1f}" if days > 0 else "0"
    stats_html = f'''<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px;">
        <div style="background:#262640;border-radius:12px;padding:16px;text-align:center;">
            <div style="color:#60a5fa;font-size:28px;font-weight:800;">{days}</div>
            <div style="color:#a1a1aa;font-size:10px;text-transform:uppercase;letter-spacing:1px;">Days Monitored</div>
        </div>
        <div style="background:#262640;border-radius:12px;padding:16px;text-align:center;">
            <div style="color:#f59e0b;font-size:28px;font-weight:800;">{obs_count}</div>
            <div style="color:#a1a1aa;font-size:10px;text-transform:uppercase;letter-spacing:1px;">Observations</div>
        </div>
        <div style="background:#262640;border-radius:12px;padding:16px;text-align:center;">
            <div style="color:#ef4444;font-size:28px;font-weight:800;">{gaps_count}</div>
            <div style="color:#a1a1aa;font-size:10px;text-transform:uppercase;letter-spacing:1px;">Gaps Observed</div>
        </div>
        <div style="background:#262640;border-radius:12px;padding:16px;text-align:center;">
            <div style="color:#a78bfa;font-size:28px;font-weight:800;">{jurisdictions_count}</div>
            <div style="color:#a1a1aa;font-size:10px;text-transform:uppercase;letter-spacing:1px;">Jurisdictions</div>
        </div>
    </div>'''

    # --- 5. Timeline ---
    timeline_html = ""
    if not not_in_registry:
        streak_color = "#ef4444" if streak > 7 else "#f59e0b" if streak > 3 else "#a1a1aa"
        timeline_html = f'''<div style="margin-top:4px;display:grid;grid-template-columns:1fr 1fr;gap:8px;font-size:12px;">
            <div><span style="color:#71717a;">First observed:</span> <span style="color:#fff;font-family:monospace;">{first_seen} UTC</span></div>
            <div><span style="color:#71717a;">Last observed:</span> <span style="color:#fff;font-family:monospace;">{last_seen} UTC</span></div>
            <div><span style="color:#71717a;">Absence streak:</span> <span style="color:{streak_color};font-weight:700;">{streak} days</span></div>
            <div><span style="color:#71717a;">Observation freq:</span> <span style="color:#a1a1aa;">{freq}/day</span></div>
        </div>'''

    # --- 6. Regulatory Context (public ingredients — no computed figures) ---
    reg_ctx_html = ""
    if gaps_count > 0:
        org_id = target_id.split("/")[0] if "/" in target_id else target_id
        org_info = _ORG_PUBLIC_REVENUE.get(org_id)

        # Collect which NEC# IDs are absent
        absent_nec_ids = set()
        if tpa:
            for o in tpa.get('observations', []):
                if not o.get('is_present'):
                    absent_nec_ids.add(o.get('necessity_id', ''))
        else:
            # Fallback: use real-time NEC check results if available
            try:
                absent_nec_ids = {nid for nid, _, is_p in nec_checks if not is_p}
            except Exception:
                absent_nec_ids = set()

        # Peer comparison (dynamic from lineage graph API)
        _peer = _load_peer_comparison()
        peer_html = f'''<div style="margin-bottom:16px;padding:14px;background:rgba(124,58,237,0.12);border-radius:8px;border-left:3px solid #a78bfa;">
            <span style="color:#c4b5fd !important;font-size:12px;font-weight:700;letter-spacing:0.08em;">PEER COMPARISON</span>
            <p style="color:#fff !important;font-size:14px;margin-top:6px;">
                <strong style="color:#a78bfa !important;font-size:18px;">{_peer["doc_rate"]}%</strong> of comparable monitored models document their training data sources.
            </p>
            <p style="color:#a1a1aa !important;font-size:11px;margin-top:4px;">Source: CROVIA Lineage Graph — {_peer["total_models"]} models, {_peer["total_orgs"]} organizations analyzed. Updated daily.</p>
        </div>'''

        # Applicable regulations (only show those matching observed gaps)
        regs_rows = ""
        applicable_count = 0
        for reg in _REGULATIONS:
            matching = [n for n in reg["nec"] if n in absent_nec_ids]
            if not matching:
                continue
            applicable_count += 1
            match_tags = ' '.join(
                f'<span style="padding:2px 8px;background:rgba(239,68,68,0.2);border:1px solid rgba(239,68,68,0.4);border-radius:4px;font-size:10px;color:#fca5a5 !important;font-family:monospace;font-weight:700;">{m}</span>'
                for m in matching
            )
            regs_rows += f'''<div style="padding:14px;border:1px solid #2a2a3e;border-radius:8px;margin-bottom:10px;background:#0d0d18;">
                <div style="display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:6px;">
                    <strong style="color:#fff !important;font-size:14px;">{reg["name"]}{reg["reg"]}</strong>
                    <span style="color:#a1a1aa !important;font-size:11px;font-weight:600;">{reg["art"]}</span>
                </div>
                <p style="color:#fbbf24 !important;font-size:13px;margin-top:8px;line-height:1.6;font-style:italic;">
                    &ldquo;{reg["text"]}&rdquo;
                </p>
                <p style="color:#a1a1aa !important;font-size:12px;margin-top:6px;">Scope: {reg["scope"]}</p>
                <div style="margin-top:8px;display:flex;gap:6px;align-items:center;flex-wrap:wrap;">
                    <span style="color:#a1a1aa !important;font-size:11px;">Gaps observed:</span> {match_tags}
                </div>
                <p style="color:#71717a !important;font-size:10px;font-style:italic;margin-top:6px;">Source: {reg["src"]}</p>
            </div>'''

        regs_html = ""
        if regs_rows:
            regs_html = f'''<div style="margin-bottom:16px;">
                <span style="color:#fbbf24 !important;font-size:12px;font-weight:700;letter-spacing:0.08em;">APPLICABLE REGULATIONS ({applicable_count})</span>
                <div style="margin-top:10px;">{regs_rows}</div>
            </div>'''

        # Organization revenue (only for major public companies with SEC filings)
        org_html = ""
        if org_info and org_info.get("usd"):
            org_html = f'''<div style="margin-bottom:16px;">
                <span style="color:#60a5fa !important;font-size:12px;font-weight:700;letter-spacing:0.08em;">ORGANIZATION</span>
                <p style="color:#fff !important;font-size:14px;margin-top:8px;">
                    {org_info["legal"]} — Annual Revenue: <strong style="color:#60a5fa !important;font-size:18px;">{org_info["usd"]}</strong>
                </p>
                <p style="color:#a1a1aa !important;font-size:11px;margin-top:4px;">Source: {org_info["src"]}</p>
            </div>'''

        # PRO CTA
        pro_cta = f'''<div style="text-align:center;padding:16px;background:rgba(124,58,237,0.15);border-radius:10px;border:1px solid rgba(124,58,237,0.4);margin-top:18px;">
            <p style="color:#c4b5fd !important;font-size:13px;margin-bottom:8px;">Quantitative regulatory exposure analysis available</p>
            <a href="mailto:info@croviatrust.com?subject=CROVIA%20PRO%20%E2%80%94%20Regulatory%20Exposure%20Analysis%20%E2%80%94%20{target_id}"
               style="color:#a78bfa !important;font-weight:700;text-decoration:none;font-size:14px;">→ Contact for CROVIA PRO</a>
        </div>'''

        # Disclaimer
        disclaimer = '''<p style="color:#71717a !important;font-size:10px;font-style:italic;margin-top:12px;text-align:center;line-height:1.5;">
            This section presents published regulatory frameworks and factual observations.
            It constitutes neither legal advice nor determination of violation.
            All penalty ranges are maximum statutory amounts as published in official regulatory texts.
        </p>'''

        reg_ctx_html = f'''<div style="margin-top:24px;background:#0d0d18;border:1px solid #2a2a3e;border-radius:12px;padding:22px;">
            <div style="color:#a78bfa !important;font-weight:800;font-size:16px;margin-bottom:18px;letter-spacing:0.03em;">REGULATORY CONTEXT</div>
            {peer_html}
            {regs_html}
            {org_html}
            {pro_cta}
            {disclaimer}
        </div>'''

    # --- Assemble ---
    hf_link = f'https://huggingface.co/{target_id}'
    generated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")

    return f'''<div style="background:#1a1a2e;border-radius:16px;padding:24px;margin:12px 0;">
        <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:20px;flex-wrap:wrap;gap:8px;">
            <div>
                <div style="color:#fff;font-size:22px;font-weight:800;word-break:break-all;">{target_id}</div>
                <a href="{hf_link}" target="_blank" style="color:#8B5CF6 !important;font-size:12px;text-decoration:none;">View on HuggingFace &rarr;</a>
            </div>
            <div style="color:#71717a;font-size:11px;font-family:monospace;">Generated: {generated_at} UTC</div>
        </div>
        {stats_html}
        {timeline_html}
        {nec_html}
        {tpa_html}
        {outreach_html}
        {reg_ctx_html}
        <div style="margin-top:24px;padding-top:16px;border-top:1px solid #262640;text-align:center;">
            <div style="color:#71717a;font-size:11px;font-style:italic;">Observation, not judgment. All data from TPR Registry + public HuggingFace metadata.</div>
        </div>
    </div>'''


if gr is not None:
    with gr.Blocks(css=CSS, title="CROVIA · Registry Observer") as app:
        
        gr.HTML(HEADER_HTML)
        
        # Alert section - appears only if verified findings exist
        alert_html = gr.HTML(value=_generate_alert_html())

        gr.Markdown("## Tools")
        with gr.Row():
            tool_lookup = gr.Button("Lookup", variant="primary")
            tool_compare = gr.Button("Compare", variant="secondary")
            tool_tpa = gr.Button("TPA", variant="secondary")
            tool_ddf = gr.Button("DDF", variant="secondary")
            tool_linkage = gr.Button("Linkage", variant="secondary")
            tool_index = gr.Button("Index", variant="secondary")
            tool_pro = gr.Button("PRO", variant="secondary")

        tools_hint = gr.Markdown("", elem_classes="cta-status")

        lookup_panel = gr.Column(visible=True)
        compare_panel = gr.Column(visible=False)
        tpa_panel = gr.Column(visible=False)
        ddf_panel = gr.Column(visible=False)
        linkage_panel = gr.Column(visible=False)
        index_panel = gr.Column(visible=False)
        pro_panel = gr.Column(visible=False)

        with lookup_panel:
            models_lk, datasets_lk = _load_target_choices()
            gr.HTML('''
            <div style="background:rgba(96,165,250,0.08);border:1px solid rgba(96,165,250,0.25);border-radius:16px;padding:20px;margin:12px 0 20px;">
                <div style="color:#60a5fa;font-weight:800;font-size:16px;margin-bottom:10px;letter-spacing:0.08em;">MODEL EVIDENCE PROFILE</div>
                <p style="color:#a1a1aa;font-size:13px;margin:0;">Select any monitored target to view its full observation history, documentation gaps, temporal proofs, and outreach status.</p>
            </div>
            ''')
            with gr.Row():
                lookup_target = gr.Dropdown(
                    label="Target (model/dataset)",
                    choices=sorted(models_lk + datasets_lk),
                    allow_custom_value=True,
                    scale=3,
                )
                lookup_btn = gr.Button("Lookup", variant="primary", scale=1)
                lookup_reload = gr.Button("Reload list", variant="secondary", scale=1)
            lookup_output = gr.HTML(value='<div style="color:#71717a;text-align:center;padding:40px;font-size:14px;">Select a target from the dropdown to view its evidence profile.</div>')
            lookup_btn.click(generate_model_lookup_html, inputs=[lookup_target], outputs=lookup_output)

            def _reload_lookup_choices() -> Any:
                global _TARGET_CHOICES_CACHE
                _TARGET_CHOICES_CACHE = None
                m, d = _load_target_choices()
                return gr.update(choices=sorted(m + d))

            lookup_reload.click(_reload_lookup_choices, inputs=[], outputs=lookup_target)

        with compare_panel:
            gr.HTML('''
            <div style="background:rgba(139,92,246,0.1);border:1px solid rgba(139,92,246,0.3);border-radius:16px;padding:20px;margin:12px 0 20px;">
                <div style="color:#a78bfa;font-weight:700;font-size:16px;margin-bottom:10px;letter-spacing:0.08em;">COMPARE 2 TARGETS</div>
                <p style="color:#a1a1aa;font-size:13px;margin:0;">Compare observation patterns between two models/datasets (data from TPR Registry)</p>
            </div>
            ''')
            with gr.Row():
                target_a = gr.Textbox(label="Target A (model/dataset ID)", placeholder="meta-llama/Llama-3-8B")
                target_b = gr.Textbox(label="Target B (model/dataset ID)", placeholder="google/gemma-2-9b")
                compare_btn = gr.Button("Compare", variant="primary")
            compare_output = gr.Code(label="Comparison Result", language=None, lines=20)

        with ddf_panel:
            models, datasets = _load_target_choices()
            gr.HTML('''
            <div style="background:rgba(16,185,129,0.08);border:1px solid rgba(16,185,129,0.25);border-radius:16px;padding:20px;margin:12px 0 20px;">
                <div style="color:#34d399;font-weight:700;font-size:16px;margin-bottom:10px;letter-spacing:0.08em;">DISCLOSURE FINGERPRINT (PREVIEW)</div>
                <p style="color:#a1a1aa;font-size:13px;margin:0;">Deterministic fingerprint from public HF metadata (hash-only). Evidence-first, no inference.</p>
            </div>
            ''')
            with gr.Row():
                ddf_target = gr.Dropdown(label="Target (model/dataset)", choices=sorted(models + datasets), allow_custom_value=True)
                ddf_btn = gr.Button("Generate", variant="primary")
                ddf_reload = gr.Button("Reload list", variant="secondary")
            ddf_out = gr.Code(label="Disclosure Fingerprint", language=None, lines=22)
            ddf_btn.click(generate_disclosure_fingerprint, inputs=[ddf_target], outputs=ddf_out)

            def _reload_ddf_choices() -> Any:
                m, d = _load_target_choices()
                return gr.update(choices=sorted(m + d))

            ddf_reload.click(_reload_ddf_choices, inputs=[], outputs=ddf_target)

        with linkage_panel:
            models, datasets = _load_target_choices()
            gr.HTML('''
            <div style="background:rgba(59,130,246,0.08);border:1px solid rgba(59,130,246,0.25);border-radius:16px;padding:20px;margin:12px 0 20px;">
                <div style="color:#60a5fa;font-weight:700;font-size:16px;margin-bottom:10px;letter-spacing:0.08em;">LINKAGE PROBE (PUBLIC MENTIONS)</div>
                <p style="color:#a1a1aa;font-size:13px;margin:0;">Checks whether a model publicly declares or mentions a dataset. This does not establish usage.</p>
            </div>
            ''')
            with gr.Row():
                lp_model = gr.Dropdown(label="Model", choices=models, allow_custom_value=True)
                lp_dataset = gr.Dropdown(label="Dataset", choices=datasets, allow_custom_value=True)
                lp_btn = gr.Button("Check", variant="primary")
                lp_reload = gr.Button("Reload list", variant="secondary")
            lp_out = gr.Code(label="Linkage Probe Result", language=None, lines=22)
            lp_btn.click(linkage_probe, inputs=[lp_model, lp_dataset], outputs=lp_out)

            def _reload_linkage_choices() -> Tuple[Any, Any]:
                m, d = _load_target_choices()
                return gr.update(choices=m), gr.update(choices=d)

            lp_reload.click(_reload_linkage_choices, inputs=[], outputs=[lp_model, lp_dataset])

        with index_panel:
            gr.HTML('''
            <div style="background:rgba(251,191,36,0.08);border:1px solid rgba(251,191,36,0.25);border-radius:16px;padding:20px;margin:12px 0 20px;">
                <div style="color:#fbbf24;font-weight:700;font-size:16px;margin-bottom:10px;letter-spacing:0.08em;">📊 DISCLOSURE INDEX (WEEKLY)</div>
                <p style="color:#a1a1aa;font-size:13px;margin:0;">Aggregated disclosure statistics across monitored targets. Observational data only.</p>
            </div>
            ''')
            index_output = gr.HTML(value=_generate_index_html())
            index_refresh = gr.Button("Refresh Index", variant="secondary")
            
            def _refresh_index():
                return _generate_index_html()
            
            index_refresh.click(_refresh_index, inputs=[], outputs=[index_output])

        with tpa_panel:
            gr.HTML('''
            <div style="background:rgba(245,158,11,0.08);border:1px solid rgba(245,158,11,0.25);border-radius:16px;padding:20px;margin:12px 0 20px;">
                <div style="color:#f59e0b;font-weight:800;font-size:16px;margin-bottom:10px;letter-spacing:0.08em;">TEMPORAL PROOF OF ABSENCE (OPEN)</div>
                <p style="color:#a1a1aa;font-size:13px;margin:0;">Cryptographically verifiable proofs that specific disclosures are absent from AI model documentation. Pedersen commitments, temporally anchored, mapped to 11 regulatory jurisdictions.</p>
            </div>
            ''')
            tpa_output = gr.HTML(value=_generate_tpa_panel_html())
            tpa_refresh = gr.Button("Refresh TPA", variant="secondary")

            def _refresh_tpa():
                return _generate_tpa_panel_html()

            tpa_refresh.click(_refresh_tpa, inputs=[], outputs=[tpa_output])

        with pro_panel:
            gr.HTML('''
            <div style="background:rgba(244,63,94,0.08);border:1px solid rgba(244,63,94,0.25);border-radius:16px;padding:20px;margin:12px 0 20px;">
                <div style="color:#fb7185;font-weight:800;font-size:16px;margin-bottom:10px;letter-spacing:0.08em;">🔒 PRO (GATED)</div>
                <p style="color:#a1a1aa;font-size:13px;margin:0;">Enterprise-only tools: gated README access, rich diffs, alerts. Open Plane remains evidence-first.</p>
            </div>
            ''')
            gr.Markdown(
                "**Call to action:** PRO features are disabled in this public Space.\n\n"
                "- What you get in PRO: rich diffs, gated-readme verification, alerts/subscriptions.\n"
                "- What we never do: public scoring or judgment.\n\n"
                "If you need access, contact us at **info@croviatrust.com** to discuss a private deployment.",
            )

        with gr.Column(elem_classes="stats-section"):
            refresh_btn = gr.Button("Refresh live data", variant="secondary")
            stats_html = gr.HTML(value=generate_stats_box_html())
            merkle_html = gr.HTML(value=generate_merkle_box_html())
            merkle_timeline_html = gr.HTML(value=generate_merkle_timeline_html())
            anchor_html = gr.HTML(value=generate_truth_anchor_html())

        observations_html = gr.HTML(value=generate_observations_html())
        
        def _select_tool(next_step: str) -> Tuple[Any, Any, Any, Any, Any, Any, Any, str]:
            show_lookup = next_step == "lookup"
            show_compare = next_step == "compare"
            show_tpa = next_step == "tpa"
            show_ddf = next_step == "ddf"
            show_linkage = next_step == "linkage"
            show_index = next_step == "index"
            show_pro = next_step == "pro"
            label = f"Selected: {next_step.upper()}"
            return (
                gr.update(visible=show_lookup),
                gr.update(visible=show_compare),
                gr.update(visible=show_tpa),
                gr.update(visible=show_ddf),
                gr.update(visible=show_linkage),
                gr.update(visible=show_index),
                gr.update(visible=show_pro),
                label,
            )

        def _refresh_all() -> Tuple[str, str, str, str, str]:
            return (
                generate_stats_box_html(),
                generate_merkle_box_html(),
                generate_merkle_timeline_html(),
                generate_truth_anchor_html(),
                generate_observations_html(),
            )
        
        def compare_targets(target_a_id, target_b_id):
            """Compare 2 targets using TPR data."""
            if not target_a_id or not target_b_id:
                return "Enter both target IDs to compare."
            
            try:
                response = requests.get(f"{TPR_API_URL}/api/targets/summary", timeout=5)
                if response.status_code != 200:
                    return f"Error: Registry returned {response.status_code}"
                
                targets_data = response.json().get('targets', [])
                target_a_data = next((t for t in targets_data if t['target_id'] == target_a_id), None)
                target_b_data = next((t for t in targets_data if t['target_id'] == target_b_id), None)
                
                if not target_a_data:
                    return f"Target A '{target_a_id}' not found in registry."
                if not target_b_data:
                    return f"Target B '{target_b_id}' not found in registry."
                
                days_a = int(target_a_data.get('days_monitored', 0))
                days_b = int(target_b_data.get('days_monitored', 0))
                obs_a = int(target_a_data.get('observation_count', 0))
                obs_b = int(target_b_data.get('observation_count', 0))
                streak_a = int(target_a_data.get('absence_streak_days', 0))
                streak_b = int(target_b_data.get('absence_streak_days', 0))
                first_a = target_a_data.get('first_seen', 'N/A')[:19] if target_a_data.get('first_seen') else 'N/A'
                first_b = target_b_data.get('first_seen', 'N/A')[:19] if target_b_data.get('first_seen') else 'N/A'
                
                comparison = {
                    "target_a": target_a_id,
                    "target_b": target_b_id,
                    "days_monitored": {"a": days_a, "b": days_b, "delta": days_a - days_b},
                    "observation_count": {"a": obs_a, "b": obs_b, "delta": obs_a - obs_b},
                    "absence_streak": {"a": streak_a, "b": streak_b, "delta": streak_a - streak_b},
                    "first_seen": {"a": first_a, "b": first_b},
                    "compared_at": datetime.now(timezone.utc).isoformat()
                }
                
                fingerprint_str = json.dumps(comparison, sort_keys=True)
                fingerprint = hashlib.sha256(fingerprint_str.encode()).hexdigest()
                comparison['difference_fingerprint'] = fingerprint
                
                temporal_note = ""
                if streak_a > 7 and streak_b > 7:
                    temporal_note = f"Temporal signal: both targets show {min(streak_a, streak_b)}+ days of continuous absence. Verify timestamps and receipts via the Registry."
                elif streak_a > 7:
                    temporal_note = f"Temporal signal: Target A shows {streak_a} days of continuous absence. Verify timestamps and receipts via the Registry."
                elif streak_b > 7:
                    temporal_note = f"Temporal signal: Target B shows {streak_b} days of continuous absence. Verify timestamps and receipts via the Registry."
                elif days_a > 0 and days_b == 0:
                    temporal_note = f"Temporal signal: Target A has {days_a} monitored days while Target B has none. Verify timestamps and receipts via the Registry."
                
                output = "\n".join([
                    "============================================================",
                    "CROVIA TEMPORAL COMPARISON",
                    "============================================================",
                    "",
                    f"TARGET A: {target_a_id}",
                    f"TARGET B: {target_b_id}",
                    "",
                    "TEMPORAL METRICS",
                    f"First Seen:         A={first_a}  B={first_b}",
                    f"Days Monitored:     A={days_a}  B={days_b}  Delta={days_a - days_b}",
                    f"Observation Count:  A={obs_a}  B={obs_b}  Delta={obs_a - obs_b}",
                    f"Absence Streak:     A={streak_a}  B={streak_b}  Delta={streak_a - streak_b}",
                    "",
                    "TEMPORAL NOTE",
                    temporal_note if temporal_note else "Temporal patterns within normal variance.",
                    "",
                    "DIFFERENCE FINGERPRINT",
                    fingerprint,
                    "",
                    f"Compared: {comparison['compared_at'][:19]}Z",
                    "Source: TPR Registry (https://registry.croviatrust.com)",
                    "Note: This is observation data, not judgment.",
                ])
                return output
                
            except Exception as e:
                return f"Error comparing targets: {type(e).__name__}: {e}"
        
        compare_btn.click(
            compare_targets,
            inputs=[target_a, target_b],
            outputs=compare_output
        )

        refresh_btn.click(
            _refresh_all,
            inputs=[],
            outputs=[stats_html, merkle_html, merkle_timeline_html, anchor_html, observations_html],
        )
        
        _tool_outputs = [lookup_panel, compare_panel, tpa_panel, ddf_panel, linkage_panel, index_panel, pro_panel, tools_hint]
        tool_lookup.click(lambda: _select_tool("lookup"), inputs=[], outputs=_tool_outputs)
        tool_compare.click(lambda: _select_tool("compare"), inputs=[], outputs=_tool_outputs)
        tool_tpa.click(lambda: _select_tool("tpa"), inputs=[], outputs=_tool_outputs)
        tool_ddf.click(lambda: _select_tool("ddf"), inputs=[], outputs=_tool_outputs)
        tool_linkage.click(lambda: _select_tool("linkage"), inputs=[], outputs=_tool_outputs)
        tool_index.click(lambda: _select_tool("index"), inputs=[], outputs=_tool_outputs)
        tool_pro.click(lambda: _select_tool("pro"), inputs=[], outputs=_tool_outputs)
        
        gr.HTML(FOOTER_HTML)

if __name__ == "__main__":
    if gr is None:
        raise SystemExit("gradio is not installed. Install gradio to launch the UI.")
    app.launch()