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cc
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
"""
Meridian - Historical Image Generator

Takes coordinates and dates, finds historical events, and generates images of those moments.
Built for the Hugging Face MCP Hackathon.
"""

import os
import warnings
from datetime import datetime
from typing import Dict, List, Optional, Tuple

# Suppress FutureWarnings for cleaner logs
warnings.filterwarnings("ignore", category=FutureWarning)

import gradio as gr
from PIL import Image
from huggingface_hub import InferenceClient
import google.generativeai as genai

from services.history_service import (
    build_event_context,
    format_event_digest,
    get_artifacts_for_year,
    get_event_by_name,
    get_event_by_slug,
    get_event_by_qid,
    get_events_by_coordinates,
    get_events_response,
    get_era_vocabulary,
    get_region_context,
    initialize_history,
    search_events_globally,
)

# Import Wikidata service for MCP tools
try:
    from services.wikidata_service import (
        mcp_search_historical_events,
        mcp_get_event_by_qid,
    )
    WIKIDATA_MCP_AVAILABLE = True
except ImportError:
    WIKIDATA_MCP_AVAILABLE = False
from services.prompt_parser import parse_prompt_context, ParsedPrompt


def join_list(items: List[str], conjunction: str = "and") -> str:
    cleaned = [item for item in items if item]
    if not cleaned:
        return ""
    if len(cleaned) == 1:
        return cleaned[0]
    if len(cleaned) == 2:
        return f"{cleaned[0]} {conjunction} {cleaned[1]}"
    return ", ".join(cleaned[:-1]) + f", {conjunction} {cleaned[-1]}"


def describe_time_of_day(hour: Optional[int]) -> str:
    if hour is None:
        return "ambient daylight with balanced, neutral lighting"
    hour = int(hour) % 24
    if 0 <= hour < 4:
        return "pre-dawn darkness punctuated by sparse artificial lights"
    if 4 <= hour < 6:
        return "blue-hour twilight with faint glow along the horizon"
    if 6 <= hour < 10:
        return "soft morning light casting long, gentle shadows"
    if 10 <= hour < 15:
        return "bright midday sunlight with crisp contrast and vivid color"
    if 15 <= hour < 18:
        return "warm late-afternoon sun gilding the scene with golden highlights"
    if 18 <= hour < 20:
        return "dusk with saturated skies and streetlights beginning to glow"
    if 20 <= hour < 23:
        return "nighttime illumination from electric signage and floodlights"
    return "deep night with high-contrast spotlights and reflective surfaces"


def describe_season(latitude: float, month: Optional[int]) -> str:
    if month is None or month < 1 or month > 12:
        return "seasonal atmosphere typical for the region"
    northern = latitude >= 0
    if northern:
        if month in [12, 1, 2]:
            return "winter air with visible breath, bundled clothing, and muted vegetation"
        if month in [3, 4, 5]:
            return "spring freshness with blooming foliage and newly awakened colors"
        if month in [6, 7, 8]:
            return "summer warmth with lush greenery and vibrant skylines"
        return "autumn chill with turning leaves and cool breezes"
    else:
        if month in [12, 1, 2]:
            return "southern hemisphere summer with bright skies and humid air"
        if month in [3, 4, 5]:
            return "autumn hues with cooling evenings and amber light"
        if month in [6, 7, 8]:
            return "winter clarity with crisp air and softer daylight"
        return "spring renewal with emerging blossoms and mild winds"


def add_composition_cues(mood: str, event_type: str = "") -> str:
    """Returns composition cues for the selected style."""
    composition_map = {
        "Documentary": "wide angle view, documentary photography style, centered composition",
        "Dramatic": "dramatic perspective, cinematic framing, rule of thirds, leading lines",
        "Artistic": "artistic composition, balanced framing, visual depth",
        "Cinematic": "cinematic wide shot, dramatic shadows, foreground action, background architecture",
        "Photojournalistic": "photojournalistic style, candid framing, natural lighting",
        "Cartoon": "animated style, vibrant colors, cartoon illustration, bold outlines",
        "Minecraft": "blocky pixelated style, minecraft aesthetic, cubic forms, voxel art",
        "Retro": "vintage photography style, retro color grading, film grain, nostalgic atmosphere",
        "Glitch": "digital glitch art, motion blur effects, halftone dot patterns, RGB channel separation, pixelated distortion, cyberpunk aesthetic, data corruption visual effects",
    }
    
    base_cue = composition_map.get(mood, "wide angle view, cinematic framing")
    
    # Only add depth cues for photorealistic styles
    if mood in ["Documentary", "Cinematic", "Dramatic", "Photojournalistic", "Artistic"]:
        depth_cues = "foreground action, middle ground figures, background architecture, atmospheric depth"
        return f"{base_cue}, {depth_cues}"
    
    return base_cue


def build_event_sections(
    event: dict,
    time_desc: str,
    season_desc: str,
    mood: str,
    lat: float,
    lon: float,
    year: int,
) -> Dict[str, str]:
    """Build VISUAL-FIRST event description for image generation.

    Returns concrete visual elements that image models understand.
    Target: 35-50 words for base prompt (style adds 15-20 more).
    """

    event_name = event.get("name", "Historical scene")
    event_year = event.get("year", year)
    location = get_location_name(event, lat, lon)

    # VISUAL SUBJECT (what the image shows)
    subject_type = "historical scene"
    if "battle" in event_name.lower() or "war" in event_name.lower():
        subject_type = "battlefield"
    elif "signing" in event_name.lower() or "declaration" in event_name.lower():
        subject_type = "formal ceremony"
    elif "speech" in event_name.lower() or "address" in event_name.lower():
        subject_type = "public gathering"
    elif "fall" in event_name.lower() or "liberation" in event_name.lower():
        subject_type = "crowd scene"

    # PARTICIPANTS (who's in the image with period clothing)
    actors = event.get("actors") or []
    participants_desc = ""
    if actors:
        # Add period-specific clothing descriptors
        clothing = get_period_clothing(event_year)
        if len(actors) == 1:
            participants_desc = f"{actors[0]} in {clothing}"
        elif len(actors) == 2:
            participants_desc = f"{actors[0]} and {actors[1]} in {clothing}"
        else:
            participants_desc = f"{actors[0]}, {actors[1]}, and others in {clothing}"

    # ENVIRONMENT (where the scene takes place)
    location_desc = get_environment_description(location, event_name, event_year)

    # VISUAL ELEMENTS (period artifacts, architecture)
    artifacts = event.get("artifacts") or []
    visual_elements = join_list(artifacts[:3], "and") if artifacts else ""

    # LIGHTING (time-based atmospheric description)
    lighting = time_desc  # Use full description

    return {
        "subject": subject_type,
        "participants": participants_desc,
        "location": location_desc,
        "elements": visual_elements,
        "lighting": lighting,
        "event_name": event_name,  # Keep for fallback
    }


def get_period_clothing(year: int) -> str:
    """Get period-appropriate clothing description."""
    if year < 1500:
        return "medieval robes and tunics"
    elif year < 1700:
        return "Renaissance doublets and robes"
    elif year < 1800:
        return "18th century coats and breeches"
    elif year < 1850:
        return "early 19th century military uniforms"
    elif year < 1900:
        return "Victorian formal attire"
    elif year < 1920:
        return "Edwardian formal dress"
    elif year < 1950:
        return "1940s military uniforms"
    elif year < 1980:
        return "mid-century formal wear"
    else:
        return "modern formal attire"


def get_environment_description(location: str, event_name: str, year: int) -> str:
    """Get concrete environmental description."""
    if "°" in location:
        env_name = ""
    else:
        env_name = location

    if "battle" in event_name.lower() or "war" in event_name.lower():
        if year < 1900:
            return f"{env_name} countryside with period cannons, military encampments, and smoke from musket fire" if env_name else "muddy battlefield with period cannons, military encampments, and gunpowder smoke"
        else:
            return f"{env_name} terrain with military vehicles, fortifications, and artillery" if env_name else "war-torn terrain with military vehicles, fortifications, and artillery smoke"
    elif "palace" in location.lower() or "hall" in event_name.lower():
        return "grand ornate interior with period chandeliers, decorative architecture, and formal furnishings"
    elif "street" in event_name.lower() or "crowd" in event_name.lower() or "fall" in event_name.lower():
        return f"{env_name} streets with period buildings, gathered crowds, and urban architecture" if env_name else "city streets with period buildings, gathered crowds, and architectural details"
    else:
        return f"{env_name} with historically accurate period architecture and setting" if env_name else "period-accurate setting with appropriate historical architecture"


def assemble_prompt_from_sections(sections: Dict[str, str], quality: str) -> str:
    """Assemble VISUAL-FIRST prompt for image generation.

    Format: "[Subject] showing [participants]. [Environment with elements]. [Lighting]."
    NO metadata - only visual descriptions that models understand.
    """

    subject = sections.get("subject", "historical scene")
    participants = sections.get("participants", "")
    location = sections.get("location", "")
    elements = sections.get("elements", "")
    lighting = sections.get("lighting", "")

    # Build prompt sentence by sentence
    parts = []

    # Sentence 1: Subject + Participants
    if participants:
        parts.append(f"{subject.capitalize()} showing {participants}")
    else:
        event_name = sections.get("event_name", "historical event")
        parts.append(f"{subject.capitalize()} depicting {event_name}")

    # Sentence 2: Environment WITH Elements (combined)
    if location and elements:
        parts.append(f"{location} with {elements}")
    elif location:
        parts.append(location)
    elif elements:
        parts.append(f"Scene with {elements}")

    # Sentence 3: Lighting/Atmosphere
    if lighting:
        parts.append(f"{lighting}")

    # Join all parts with periods for clear structure
    final = ". ".join(parts)

    return final.strip()


def build_fallback_prompt(
    lat: float,
    lon: float,
    year: int,
    month: int,
    day: int,
    hour: int,
    mood: str,
) -> Tuple[str, str]:
    time_desc = describe_time_of_day(hour)
    season_desc = describe_season(lat, month)
    vocab = get_era_vocabulary(year)
    artifact_titles = [artifact["title"] for artifact in get_artifacts_for_year(year, limit=3)]
    sections = {
        "scene": f"{mood} depiction of daily life near {lat:.2f}, {lon:.2f} in {year}.",
        "participants": "Participants include residents, traders, and travelers in their everyday routines.",
        "environment": (
            f"Environment frames {vocab.get('architecture')} under {time_desc} and {season_desc}."
        ),
        "elements": (
            f"Visible elements: {join_list(artifact_titles)}."
            if artifact_titles
            else f"Technology of the era includes {vocab.get('technology')} and {vocab.get('transport')}."
        ),
    }
    # Style-appropriate quality tags
    if mood in ["Cartoon", "Minecraft", "Retro", "Glitch"]:
        quality_map = {
            "Cartoon": "cartoon illustration style, vibrant colors, bold outlines, historically inspired",
            "Minecraft": "minecraft blocky style, pixelated, cubic forms, historically themed",
            "Retro": "retro vintage style, film grain, nostalgic color grading, historically accurate",
            "Glitch": "digital glitch art style, cyberpunk aesthetic, data corruption effects, historically themed"
        }
        quality = quality_map.get(mood, f"{mood} style, historically inspired")
    else:
        quality = f"{mood} style, historically accurate, photorealistic, 8K"
    prompt = assemble_prompt_from_sections(sections, quality)
    hint = (
        f"📍 {lat:.4f}, {lon:.4f} | 📅 {year}-{month:02d}-{day:02d} {hour:02d}:00\n"
        "ℹ️ No curated event match found; using era vocabulary fallback."
    )
    return prompt, hint

# Load environment variables
try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    pass

# ==========================
# SSL Certificate Fix
# ==========================
# Fix SSL certificate issues on macOS/Anaconda
try:
    import certifi
    cert_path = certifi.where()
    if cert_path and os.path.exists(cert_path):
        os.environ.setdefault("SSL_CERT_FILE", cert_path)
        os.environ.setdefault("REQUESTS_CA_BUNDLE", cert_path)
        os.environ.setdefault("CURL_CA_BUNDLE", cert_path)
except ImportError:
    pass

# ==========================
# Configuration
# ==========================

# Try both common environment variable names for HF token
HF_TOKEN = (os.getenv("HUGGINGFACE_API_TOKEN") or os.getenv("HF_TOKEN", "")).strip()
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "").strip()

# Display token status on startup
print("\n" + "="*60)
print("🔑 API Token Status:")
print("="*60)
if HF_TOKEN:
    print(f"✅ HF_TOKEN: Found ({len(HF_TOKEN)} chars) - {HF_TOKEN[:10]}...")
else:
    print("❌ HF_TOKEN: Not found!")
    print("   Set HUGGINGFACE_API_TOKEN or HF_TOKEN environment variable")

if GEMINI_API_KEY:
    print(f"✅ GEMINI_API_KEY: Found ({len(GEMINI_API_KEY)} chars) - {GEMINI_API_KEY[:10]}...")
    genai.configure(api_key=GEMINI_API_KEY)
else:
    print("⚠️  GEMINI_API_KEY: Not found (prompts will use fallback)")
print("="*60 + "\n")

# Image generation models
IMAGE_MODELS = {
    "FLUX.1-dev (High Quality)": "black-forest-labs/FLUX.1-dev",
    "FLUX.1-schnell (Fast)": "black-forest-labs/FLUX.1-schnell",
}

# ==========================
# Negative Prompts by Era (Prevent Anachronisms)
# ==========================

NEGATIVE_PROMPTS_BY_ERA = {
    (-5000, 500): "modern clothing, eyeglasses, wristwatches, cars, trains, airplanes, electric lights, smartphones, cameras, plastic, metal zippers, sneakers, jeans, t-shirts, hoodies, sunglasses, baseball caps, medieval armor, Renaissance art style",
    (500, 1500): "Renaissance art style, modern clothing, eyeglasses, wristwatches, cars, trains, airplanes, electric lights, smartphones, cameras, plastic, metal zippers, sneakers, jeans, t-shirts, hoodies, sunglasses, baseball caps, printing press, gunpowder weapons",
    (1500, 1800): "cars, motorcycles, airplanes, electric lights, smartphones, modern electronics, plastic materials, synthetic fabrics, LED screens, digital devices, neon signs, concrete buildings, steel skyscrapers, industrial machinery",
    (1800, 1900): "cars, motorcycles, airplanes, electric lights, smartphones, modern electronics, plastic materials, synthetic fabrics, LED screens, digital devices, neon signs, concrete buildings, steel skyscrapers, modern vehicles",
    (1900, 1940): "smartphones, laptops, computers, LED lights, jet aircraft, modern cars (post-1940), plastic bottles, digital screens, television, contemporary architecture, synthetic clothing, polyester, atomic age technology",
    (1940, 1970): "smartphones, tablets, computers, personal electronics, LED billboards, 1980s fashion, digital displays, modern vehicles (post-1970), synthesizers, disco fashion, platform shoes, personal computers",
    (1970, 2000): "smartphones, tablets, laptops, modern electronics (post-2000), contemporary fashion, LED screens, modern architecture (post-2000), flat screen monitors, wireless devices, social media",
    (2000, 2100): "futuristic technology, holograms, flying cars, sci-fi elements, unrealistic technology, augmented reality interfaces, cyberpunk aesthetics, AI robots"
}

# FLUX-specific negative prompts (always included)
FLUX_NEGATIVE_BASE = "cartoon, illustration, painting, drawing, sketch, low quality, blurry, distorted, watermark, text, signature, jpeg artifacts, pixelated, bad anatomy, deformed, ugly, duplicate, morbid, mutilated, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck"

def get_negative_prompt(year: int) -> str:
    """Returns negative prompt to prevent anachronisms for the given year."""
    era_negatives = ""
    for (start, end), negatives in NEGATIVE_PROMPTS_BY_ERA.items():
        if start <= year < end:
            era_negatives = negatives
            break
    if not era_negatives:
        era_negatives = NEGATIVE_PROMPTS_BY_ERA[(1970, 2000)]  # Default
    
    # Combine era-specific and FLUX base negatives
    return f"{FLUX_NEGATIVE_BASE}, {era_negatives}"

# ==========================
# AI Prompt Generation
# ==========================

def generate_historical_prompt(
    lat: float,
    lon: float,
    year: int,
    month: int,
    day: int,
    hour: int,
    mood: str = "Documentary",
) -> Tuple[str, str]:
    """Finds historical events and builds a prompt for image generation."""

    # Find events near the coordinates, prioritizing exact year matches
    events = get_events_by_coordinates(
        lat, lon, year,
        radius_km=400,
        limit=4,
        include_wikidata=True,
        year_weight=1.5,
    )
    time_desc = describe_time_of_day(hour)
    season_desc = describe_season(lat, month)

    if events:
        focus_event = events[0]
        sections = build_event_sections(focus_event, time_desc, season_desc, mood, lat, lon, year)
        # Style-appropriate quality tags
        if mood in ["Cartoon", "Minecraft", "Retro", "Glitch"]:
            quality_map = {
                "Cartoon": "cartoon illustration style, vibrant colors, bold outlines, historically inspired",
                "Minecraft": "minecraft blocky style, pixelated, cubic forms, historically themed",
                "Retro": "retro vintage style, film grain, nostalgic color grading, historically accurate",
                "Glitch": "digital glitch art style, cyberpunk aesthetic, data corruption effects, historically themed"
            }
            quality = quality_map.get(mood, f"{mood} style, historically inspired")
        else:
            quality = f"{mood} style, historically accurate, photorealistic, 8K"
        prompt = assemble_prompt_from_sections(sections, quality)

        # Show where the event came from
        source = focus_event.get("source", "curated")
        source_badge = "📚 Curated" if source == "curated" else "🌐 Wikidata"
        qid = focus_event.get("qid", "")
        source_info = f"{source_badge}"
        if qid:
            source_info += f" ({qid})"
        
        # Show how close the year match is
        year_delta = focus_event.get("year_delta", 0)
        if year_delta == 0:
            year_match = "🎯 Exact year match!"
        elif year_delta <= 2:
            year_match = f"📅 ±{year_delta} year(s)"
        elif year_delta <= 5:
            year_match = f"📅 ~{year_delta} years"
        elif year_delta <= 10:
            year_match = f"📅 ~{year_delta} years apart"
        else:
            year_match = f"⚠️ {year_delta} years apart"

        hint_lines = [
            f"📍 {lat:.4f}, {lon:.4f} | 📅 {year}-{month:02d}-{day:02d} {hour:02d}:00",
            (
                f"🎯 Focus event: {focus_event['name']} ({focus_event.get('year')}) · "
                f"{focus_event.get('distance_km')}km · {year_match} · {source_info}"
            ),
        ]
        summary = focus_event.get("summary") or focus_event.get("narrative") or focus_event.get("description")
        if summary:
            hint_lines.append(f"📝 {summary[:200]}{'...' if len(summary) > 200 else ''}")
        
        # Show participants if available
        participants = focus_event.get("actors") or focus_event.get("participants") or []
        if participants:
            hint_lines.append(f"👥 Participants: {', '.join(participants[:5])}")
        
        if len(events) > 1:
            hint_lines.append("📚 Related possibilities:")
            for related in events[1:]:
                rel_source = "📚" if related.get("source") == "curated" else "🌐"
                hint_lines.append(
                    f"- {rel_source} {related['name']} ({related.get('year')}) · {related.get('distance_km')}km · "
                    f"conf {related.get('match_confidence', 0):.2f}"
                )
        hint = "\n".join(hint_lines)
        return prompt, hint

    # Fallback when no curated event is close enough
    return build_fallback_prompt(lat, lon, year, month, day, hour, mood)

# ==========================
# Image Generation
# ==========================

def generate_image(prompt: str, model_key: str, year: int = None, negative_prompt: str = None) -> Tuple[Optional[Image.Image], str]:
    """Generates image using FLUX via Hugging Face API. Auto-generates negative prompts based on year if not provided."""
    
    if not HF_TOKEN:
        error_msg = """❌ Hugging Face API token not configured!

Please set one of these environment variables:
• HUGGINGFACE_API_TOKEN='your_token_here'
• HF_TOKEN='your_token_here'

Get your token at: https://huggingface.co/settings/tokens"""
        return None, error_msg
    
    model_id = IMAGE_MODELS.get(model_key, IMAGE_MODELS["FLUX.1-dev (High Quality)"])
    
    # Generate negative prompt if not provided and year is available
    if negative_prompt is None and year is not None:
        negative_prompt = get_negative_prompt(year)
    
    try:
        client = InferenceClient(token=HF_TOKEN)
        
        start_time = datetime.now()
        
        # Build parameters
        params = {
            "prompt": prompt,
            "model": model_id,
            "width": 1024,
            "height": 768,
        }
        
        # Add negative prompt if available (FLUX supports it)
        if negative_prompt:
            params["negative_prompt"] = negative_prompt
        
        image = client.text_to_image(**params)
        elapsed = (datetime.now() - start_time).total_seconds()
        
        status = f"✅ Generated in {elapsed:.1f}s using {model_key}"
        if negative_prompt:
            status += " (with era-appropriate exclusions)"
        return image, status

    except Exception as e:
        error_msg = f"❌ Generation failed: {str(e)}"
        # Add helpful context for common errors
        if "rate limit" in str(e).lower():
            error_msg += "\n\n💡 Tip: Try FLUX.1-schnell (faster) or wait a few minutes."
        elif "timeout" in str(e).lower():
            error_msg += "\n\n💡 Tip: Model loading. Try again in 30 seconds."
        return None, error_msg

# ==========================
# Main Workflow
# ==========================

def process_coordinates(lat: float, lon: float, year: int, month: int, day: int, hour: int, mood: str, model_key: str, custom_prompt: str = None):
    """Main workflow: takes coordinates and date, generates prompt and image."""
    
    # Generate prompt or use custom one
    status_parts = []
    if custom_prompt and custom_prompt.strip():
        prompt = custom_prompt.strip()
        hint = f"📍 {lat:.4f}, {lon:.4f} | 📅 {year}-{month:02d}-{day:02d} {hour}:00 (Custom prompt)"
        status_parts.append("✅ Using custom prompt")
    else:
        status_parts.append("🔍 Searching historical events...")
        prompt, hint = generate_historical_prompt(lat, lon, year, month, day, hour, mood)
        status_parts.append("✅ Prompt generated")
    
    # Generate the image
    status_parts.append(f"🎨 Generating image with {model_key}...")
    image, gen_status = generate_image(prompt, model_key, year=year)
    status_parts.append(gen_status)
    
    # Build timeline of nearby events
    status_parts.append("📚 Building historical timeline...")
    events = get_events_by_coordinates(
        lat, lon, year,
        radius_km=500,
        limit=5,
        include_wikidata=True,
        year_weight=1.5,
    )
    status_parts.append(f"✅ Found {len(events)} nearby events")
    
    status = " | ".join(status_parts)
    
    timeline_md = "### Nearby Historical Events\n\n"
    if events:
        for event in events:
            source = event.get("source", "curated")
            source_icon = "📚" if source == "curated" else "🌐"
            qid = event.get("qid", "")
            qid_link = f" [[{qid}](https://www.wikidata.org/wiki/{qid})]" if qid else ""
            
            # Year match indicator
            year_delta = event.get("year_delta", 0)
            if year_delta == 0:
                year_badge = "🎯"
            elif year_delta <= 5:
                year_badge = "📅"
            else:
                year_badge = "⏳"

            timeline_md += (
                f"**{event.get('year')}** {year_badge}{source_icon} {event.get('name')}{qid_link} "
                f"({event.get('distance_km')}km"
            )
            if year_delta > 0:
                timeline_md += f" · ±{year_delta}yr"
            timeline_md += f")\n\n"
            
            summary = event.get("summary") or event.get("narrative") or event.get("description")
            if summary:
                timeline_md += f"> {summary[:180]}{'...' if len(summary) > 180 else ''}\n\n"
            
            # Show participants for Wikidata events
            participants = event.get("actors") or event.get("participants") or []
            if participants and source == "wikidata":
                timeline_md += f"_Participants: {', '.join(participants[:4])}_\n\n"
        else:
            timeline_md += "_No specific events found in database or Wikidata. Scene generated from era-appropriate context._"
    
    return image, prompt, hint, status, timeline_md

# ==========================
# Gradio UI
# ==========================

def create_app():
    """Sets up the Gradio UI."""
    
    # Initialize history dataset and store
    initialize_history()
    
    # Hybrid Theme: Warm Hero + Clean Readable Content
    # Hero uses Peach/Lavender/Sky Blue gradient
    # Content areas use high-contrast, professional styling
    custom_css = """
    :root {
        /* Hero colors (warm palette) */
        --peach: #ffad7a;
        --peach-dark: #e8935c;
        --lavender: #b8a9d9;
        --sky-blue: #7ACCFF;
        
        /* Content colors (high contrast, professional) */
        --bg-light: #f9fafb;
        --surface: #ffffff;
        --text-primary: #1f2937;
        --text-secondary: #4b5563;
        --text-muted: #6b7280;
        --border-default: #e5e7eb;
        --border-subtle: #f3f4f6;
        
        /* Accent (peach for interactive elements) */
        --accent: #ffad7a;
        --accent-hover: #e8935c;
        --accent-subtle: rgba(255, 173, 122, 0.1);

        /* Shadows */
        --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
        --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);
        --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.12);
    }
    
    /* Base - Clean, readable */
    body {
        background: var(--bg-light) !important;
        color: var(--text-primary) !important;
        font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'Segoe UI', Roboto, sans-serif !important;
        -webkit-font-smoothing: antialiased;
    }

    .gradio-container {
        max-width: 100% !important;
        background: var(--bg-light) !important;
    }
    
    /* ========== HERO - Warm gradient (kept from new design) ========== */
    .hero {
        text-align: center;
        padding: 2.5rem 2rem;
        background: linear-gradient(135deg, var(--peach) 0%, var(--lavender) 50%, var(--sky-blue) 100%);
        border-radius: 20px;
        margin: 1rem;
        box-shadow: var(--shadow-lg), 0 0 30px rgba(255, 173, 122, 0.2);
        position: relative;
        overflow: hidden;
    }
    
    .hero::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: radial-gradient(ellipse at 30% 20%, rgba(255,255,255,0.35) 0%, transparent 50%);
        pointer-events: none;
    }
    
    .hero h1 {
        font-size: 2.75rem;
        font-weight: 600;
        color: #ffffff !important;
        margin-bottom: 0.5rem;
        text-shadow: 0 2px 8px rgba(0,0,0,0.15);
        letter-spacing: -0.03em;
        position: relative;
        font-family: 'Inter', 'Helvetica Neue', system-ui, sans-serif;
    }
    
    .hero p {
        color: rgba(255, 255, 255, 0.95);
        font-size: 1.1rem;
        font-weight: 450;
        position: relative;
    }
    
    /* ========== CONTENT AREAS - Clean, high contrast ========== */
    
    /* Layout */
    .main-grid {
        display: grid;
        grid-template-columns: 320px 1fr;
        gap: 1.5rem;
        padding: 1rem;
    }
    
    /* Sidebar - Clean white */
    .sidebar {
        background: var(--surface);
        border-radius: 12px;
        padding: 1.5rem;
        border: 1px solid var(--border-default);
        box-shadow: var(--shadow-md);
        height: fit-content;
        position: sticky;
        top: 1rem;
    }
    
    /* Main Panel - Clean white */
    .main-panel {
        background: var(--surface);
        border-radius: 12px;
        padding: 1.5rem;
        border: 1px solid var(--border-default);
        box-shadow: var(--shadow-md);
    }
    
    /* Inputs - Clean with peach focus */
    input, select, textarea {
        background: var(--bg-light) !important;
        border: 1px solid var(--border-default) !important;
        color: var(--text-primary) !important;
        border-radius: 8px !important;
        transition: all 0.15s ease !important;
    }
    
    input:focus, select:focus, textarea:focus {
        border-color: var(--accent) !important;
        box-shadow: 0 0 0 3px var(--accent-subtle) !important;
        outline: none !important;
    }
    
    /* Buttons - Peach gradient (elegant touch) */
    button {
        background: linear-gradient(135deg, var(--accent) 0%, var(--accent-hover) 100%) !important;
        color: #ffffff !important;
        font-weight: 600 !important;
        border: none !important;
        border-radius: 10px !important;
        padding: 0.75rem 1.5rem !important;
        transition: all 0.2s ease !important;
        box-shadow: 0 2px 8px rgba(255, 173, 122, 0.3) !important;
    }
    
    button:hover {
        background: linear-gradient(135deg, var(--accent-hover) 0%, #d67d45 100%) !important;
        transform: translateY(-1px) !important;
        box-shadow: 0 4px 16px rgba(255, 173, 122, 0.4) !important;
    }
    
    /* Labels - High contrast */
    label {
        color: var(--text-secondary) !important;
        font-weight: 500 !important;
        font-size: 0.875rem !important;
    }
    
    /* Section headers - Clear hierarchy */
    .markdown-text h3, h3 {
        color: var(--text-primary) !important;
        font-weight: 600 !important;
        font-size: 1rem !important;
        margin-bottom: 0.5rem !important;
    }
    
    /* All markdown text - Ensure readability */
    .markdown-text, .markdown-text p, .markdown-text span {
        color: var(--text-primary) !important;
    }
    
    .markdown-text strong {
        color: var(--text-primary) !important;
        font-weight: 600 !important;
    }
    
    /* Image container - Enhanced with animations */
    .gr-image {
        border-radius: 12px !important;
        border: 1px solid var(--border-default) !important;
        box-shadow: var(--shadow-md) !important;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
        opacity: 0;
        animation: fadeInImage 0.6s ease-out forwards !important;
    }
    
    @keyframes fadeInImage {
        from {
            opacity: 0;
            transform: translateY(10px) scale(0.98);
        }
        to {
            opacity: 1;
            transform: translateY(0) scale(1);
        }
    }
    
    .gr-image:hover {
        border-color: var(--accent) !important;
        box-shadow: 0 8px 24px rgba(255, 173, 122, 0.3) !important;
        transform: translateY(-2px) scale(1.01) !important;
    }
    
    /* Hint/status text - Subtle background, readable text with smooth transitions */
    .hint-text {
        font-size: 0.9rem;
        color: var(--text-secondary);
        padding: 0.875rem 1rem;
        background: var(--bg-light);
        border-radius: 8px;
        border: 1px solid var(--border-default);
        margin-top: 0.5rem;
        line-height: 1.6;
        transition: all 0.3s ease !important;
        animation: slideInHint 0.4s ease-out !important;
    }
    
    @keyframes slideInHint {
        from {
            opacity: 0;
            transform: translateX(-10px);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }
    
    /* Accordion */
    .gr-accordion {
        background: var(--surface) !important;
        border: 1px solid var(--border-default) !important;
        border-radius: 8px !important;
    }
    
    /* Blockquotes - Subtle lavender touch */
    blockquote, .markdown-text blockquote {
        border-left: 3px solid var(--lavender) !important;
        background: #faf9fc !important;
        padding: 0.75rem 1rem !important;
        margin: 0.5rem 0 !important;
        border-radius: 0 6px 6px 0 !important;
        color: var(--text-secondary) !important;
    }
    
    /* Links - Sky blue */
    a {
        color: #2563eb !important;
        text-decoration: none !important;
    }
    
    a:hover {
        color: var(--accent-hover) !important;
        text-decoration: underline !important;
    }
    
    /* Slider */
    input[type="range"] {
        accent-color: var(--accent) !important;
    }
    
    /* Loading states - Enhanced */
    .generating {
        position: relative;
        overflow: hidden;
    }

    .generating::after {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,173,122,0.2), transparent);
        animation: loading 1.5s infinite;
    }

    @keyframes loading {
        0% { left: -100%; }
        100% { left: 100%; }
    }

    /* Skeleton loader for image placeholder */
    .image-skeleton {
        width: 100%;
        height: 600px;
        background: linear-gradient(90deg, 
            var(--bg-light) 0%, 
            var(--border-subtle) 50%, 
            var(--bg-light) 100%);
        background-size: 200% 100%;
        border-radius: 12px;
        animation: skeleton-loading 1.5s ease-in-out infinite;
    }

    @keyframes skeleton-loading {
        0% { background-position: 200% 0; }
        100% { background-position: -200% 0; }
    }

    /* Progress indicator */
    .progress-bar {
        height: 4px;
        background: linear-gradient(90deg, var(--accent), var(--lavender));
        border-radius: 2px;
        animation: progress 2s ease-in-out infinite;
        margin: 1rem 0;
    }

    @keyframes progress {
        0%, 100% { transform: scaleX(0.3); transform-origin: left; }
        50% { transform: scaleX(1); transform-origin: left; }
    }

    /* Status text with pulse animation */
    .status-generating {
        color: var(--accent) !important;
        font-weight: 500 !important;
        animation: pulse 2s ease-in-out infinite !important;
    }

    @keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.7; }
    }

    /* Button active state */
    button:active {
        transform: translateY(0) scale(0.98) !important;
        transition: transform 0.1s ease !important;
    }

    /* Panel entrance animation */
    .main-panel, .sidebar {
        animation: fadeInPanel 0.5s ease-out !important;
    }

    @keyframes fadeInPanel {
        from {
            opacity: 0;
            transform: translateY(20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* Smooth text transitions */
    .markdown-text {
        transition: opacity 0.3s ease !important;
    }

    /* Footer */
    footer {
        display: none !important;
    }

    /* Responsive */
    @media (max-width: 768px) {
        .main-grid {
            grid-template-columns: 1fr;
        }
        
        .sidebar {
            position: static;
        }
        
        .hero h1 {
            font-size: 2rem;
            color: #ffffff !important;
        }
    }
    """
    
    with gr.Blocks(title="Meridian — Historical Image Generator") as demo:
        # Inject custom CSS
        gr.HTML(f"<style>{custom_css}</style>")
        
        # Hero
        gr.HTML("""
        <div class="hero">
            <h1>🌍 Meridian</h1>
            <p>Generate historically accurate scenes from geospatial coordinates and date/time inputs</p>
        </div>
        """)

        with gr.Row(elem_classes="main-grid"):
            
            # Left Sidebar: Inputs
            with gr.Column(scale=1, elem_classes="sidebar"):
                gr.Markdown("### ✍️ Custom Prompt")
                prompt_override = gr.Textbox(
                    label="Describe the scene (optional)",
                    placeholder="Create an image at 31.7785° N, 35.2296° E, April 3, 33 CE, 15:00 hours",
                            lines=4,
                )
                gr.Markdown("_When filled, coordinate inputs are locked so the prompt takes precedence._")

                gr.Markdown("### 📍 Coordinates")
                latitude = gr.Number(label="Latitude", value=52.5163, step=0.0001)
                longitude = gr.Number(label="Longitude", value=13.3777, step=0.0001)
                
                gr.Markdown("### 📅 Date & Time")
                year = gr.Number(label="Year", value=1989, precision=0)
                month = gr.Number(label="Month (1-12)", value=11, precision=0, minimum=1, maximum=12)
                day = gr.Number(label="Day (1-31)", value=9, precision=0, minimum=1, maximum=31)
                hour = gr.Slider(label="Hour (0-23)", minimum=0, maximum=23, value=23, step=1)
                
                gr.Markdown("### 🎨 Style")
                mood = gr.Dropdown(
                    label="Mood/Style",
                    choices=["Documentary", "Cinematic", "Photojournalistic", "Dramatic", "Cartoon", "Minecraft", "Retro", "Glitch"],
                    value="Documentary"
                )
                
                model_choice = gr.Dropdown(
                    label="Model",
                    choices=list(IMAGE_MODELS.keys()),
                    value="FLUX.1-dev (High Quality)"
                )
                
                generate_btn = gr.Button("🎬 Generate Image", variant="primary", size="lg")
            
            # Right Main Panel: Outputs
            with gr.Column(scale=3, elem_classes="main-panel"):
                
                hint_display = gr.Markdown(
                    "Enter coordinates and date/time *or* supply a custom prompt, then click Generate.",
                    elem_classes="hint-text",
                )
                
                gr.Markdown("### 📝 Scene Description")
                gr.Markdown("_Generated prompt (appears after image generation, editable for regeneration):_")
                prompt_box = gr.Textbox(
                    label="",
                    lines=6,
                    placeholder="Prompt will appear here after generation. You can edit it and regenerate.",
                    show_label=False
                )
                
                gr.Markdown("### 🖼️ Generated Image")
                image_output = gr.Image(
                    label="",
                    show_label=False,
                    height=600,
                    type="pil"
                )
                
                status_display = gr.Markdown("_Ready to generate_", elem_classes="status-display")
                
                # How It Works - Full width section (same spacing as Generated Image section above)
                gr.Markdown("### 💡 How It Works")
                gr.Markdown("""
                Meridian transforms geographic coordinates and dates into historically accurate visual scenes through a unique three-step process:
                
                1. **Historical Event Discovery**: When you provide coordinates and a date, Meridian searches through curated historical databases and Wikidata to find events that occurred near that location and time. Using Haversine distance calculations (which account for Earth's curvature), the system identifies the most relevant historical events, prioritizing those that match your exact year.
                
                2. **Intelligent Prompt Generation**: Once a historical event is identified, Meridian creates a focused, detailed description that emphasizes the event name, location, and year—the three most critical elements for accurate image generation. The system considers time of day (affecting lighting), season, regional architecture, and key participants to build a vivid scene description.
                
                3. **Photorealistic Image Creation**: The generated prompt is sent to FLUX.1-dev, an advanced image generation model, which creates a historically accurate scene. Negative prompts automatically prevent anachronisms (like modern technology appearing in ancient scenes), ensuring period-appropriate results.
                
                All of this happens automatically—you simply enter coordinates and a date, or describe what you're looking for in natural language.
                """)
                
                # Technical Capabilities - Full width section (same spacing as Generated Image section)
                gr.Markdown("### ⚙️ Technical Capabilities")
                gr.Markdown("""
                **Solving the Geospatial Challenge**: Traditional image generation models struggle with coordinates because they tokenize numbers like "52.5163" as separate symbols rather than understanding them as geographic locations. Meridian bridges this gap by maintaining a structured geospatial-historical database that maps precise coordinates to historical events, then translating those events into rich semantic descriptions that image models understand.
                
                **Dual Data Sources**: Meridian combines a curated database of pivotal historical events with real-time Wikidata queries, providing both quality (hand-selected events with rich metadata) and breadth (comprehensive coverage of global history). Events are scored by geographic proximity, temporal accuracy, and source reliability.
                
                **Year-Weighted Matching**: The system prioritizes events that match your exact year over nearby events from different time periods. This ensures that when you request "Rome, 44 BCE," you get Julius Caesar's assassination, not a medieval event that happened at the same coordinates centuries later.
                
                **Period-Accurate Generation**: Negative prompts automatically exclude anachronistic elements based on the event's era. For example, ancient scenes won't include modern clothing or technology, while 19th-century scenes exclude digital devices. The system also adapts architectural styles, clothing, and technology to match the historical period.
                
                **Time-Aware Details**: Meridian considers the specific hour you provide (affecting lighting—dawn, midday, dusk, or night) and the month/latitude combination (determining season and atmospheric conditions) to create scenes that feel authentic to the moment in history.
                
                **MCP Integration**: Through Model Context Protocol, Meridian can be called programmatically by AI assistants like Claude, enabling automated historical visualization workflows for education, research, and content creation.
                """)
                
                with gr.Accordion("📜 Historical Timeline", open=False):
                    timeline_display = gr.Markdown("Nearby events will appear here after generation.")
        
        def on_prompt_override_change(text):
            interactive = not bool(text.strip())
            update = gr.update(interactive=interactive)
            return update, update, update, update, update, gr.update(interactive=interactive)

        prompt_override.change(
            fn=on_prompt_override_change,
            inputs=[prompt_override],
            outputs=[latitude, longitude, year, month, day, hour],
        )

        # Event handler
        def on_generate(prompt_override_text, lat, lon, yr, mon, dy, hr, mood_val, model_val, prompt_box_text):
            lat_val = float(lat) if lat is not None else 0.0
            lon_val = float(lon) if lon is not None else 0.0
            year_val = int(yr)
            month_val = int(mon)
            day_val = int(dy)
            hour_val = int(hr)
            custom_text = prompt_box_text
            derived_note = ""

            if prompt_override_text and prompt_override_text.strip():
                custom_text = prompt_override_text.strip()
                parsed: ParsedPrompt = parse_prompt_context(custom_text)
                if parsed.lat is not None and parsed.lon is not None and parsed.confidence >= 0.35:
                    lat_val = parsed.lat
                    lon_val = parsed.lon
                    if parsed.year is not None:
                        year_val = parsed.year
                    if parsed.month is not None:
                        month_val = parsed.month
                    if parsed.day is not None:
                        day_val = parsed.day
                    if parsed.hour is not None:
                        hour_val = parsed.hour % 24
                    derived_note = (
                        f"🧭 Parsed from prompt (confidence {parsed.confidence:.2f}) · "
                        f"{lat_val:.4f}, {lon_val:.4f}, year {year_val}"
                    )
            else:
                    derived_note = "⚠️ Could not confidently parse prompt context; using manual inputs."

            image, prompt, hint, status, timeline = process_coordinates(
                lat_val, lon_val, year_val, month_val, day_val, hour_val, mood_val, model_val, custom_text
            )

            if derived_note:
                hint = f"{hint}\n{derived_note}"
            if derived_note.startswith("⚠️"):
                status = f"{status}\n{derived_note}"
            elif derived_note.startswith("🧭"):
                status = f"{status}\nInterpreted prompt context successfully."
                timeline = timeline.replace(
                    "### Nearby Historical Events",
                    f"### Nearby Historical Events\n\n_Prompt-derived coordinates:_ {lat_val:.4f}, {lon_val:.4f}",
                    1,
                )

            return image, prompt, hint, status, timeline

        generate_btn.click(
            fn=on_generate,
            inputs=[prompt_override, latitude, longitude, year, month, day, hour, mood, model_choice, prompt_box],
            outputs=[image_output, prompt_box, hint_display, status_display, timeline_display]
        )
    
    return demo

# ==========================
# MCP Server Support
# ==========================

def mcp_generate_from_coordinates(
    latitude: float,
    longitude: float,
    year: int,
    month: int = 1,
    day: int = 1,
    hour: int = 12,
    mood: str = "Documentary",
    model: str = "FLUX.1-dev (High Quality)",
) -> Dict:
    """MCP tool: generates image from coordinates and date."""
    try:
        nearby_events = get_events_by_coordinates(
            latitude, longitude, year, radius_km=300, limit=5
        )
        image, prompt, hint, status, timeline = process_coordinates(
            latitude,
            longitude,
            year,
            month,
            day,
            hour,
            mood,
            model,
        )
        
        return {
            "success": True,
            "prompt": prompt,
            "hint": hint,
            "status": status,
            "image_generated": image is not None,
            "events": [format_event_digest(event) for event in nearby_events],
            "timeline_markdown": timeline,
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e)
        }


def mcp_get_events_by_coordinates(
    latitude: float,
    longitude: float,
    year: int,
    radius_km: float = 250.0,
    limit: int = 5,
) -> Dict:
    """MCP tool: finds nearby historical events."""
    try:
        payload = get_events_response(latitude, longitude, year, radius_km=radius_km, limit=limit)
        payload["success"] = True
        return payload
    except Exception as exc:
        return {"success": False, "error": str(exc)}


def mcp_get_event_context(identifier: str) -> Dict:
    """MCP tool: gets detailed info about an event by name or slug."""
    event = get_event_by_slug(identifier)
    if not event:
        event = get_event_by_name(identifier)
    if not event:
        return {"success": False, "error": f"Event '{identifier}' not found"}

    context = build_event_context(event)
    context["artifacts"] = get_artifacts_for_year(event.get("year", 0))
    context["source"] = event.get("source", "curated")
    return {"success": True, "context": context}


def mcp_search_wikidata_events(
    latitude: float,
    longitude: float,
    year: int,
    radius_km: float = 300.0,
    limit: int = 10,
) -> Dict:
    """MCP tool: searches Wikidata for events at coordinates and year."""
    if not WIKIDATA_MCP_AVAILABLE:
        return {
            "success": False,
            "error": "Wikidata service not available",
        }
    
    return mcp_search_historical_events(
        latitude=latitude,
        longitude=longitude,
        year=year,
        radius_km=radius_km,
        limit=limit,
    )


def mcp_get_wikidata_event(qid: str) -> Dict:
    """MCP tool: gets Wikidata event details by QID."""
    if not WIKIDATA_MCP_AVAILABLE:
        return {
            "success": False,
            "error": "Wikidata service not available",
        }
    
    return mcp_get_event_by_qid(qid)


def mcp_search_events_globally(
    latitude: float,
    longitude: float,
    year: int,
    radius_km: float = 500.0,
    limit: int = 10,
) -> Dict:
    """MCP tool: searches for events with wider radius, combining curated and Wikidata data."""
    try:
        events = search_events_globally(
            lat=latitude,
            lon=longitude,
            year=year,
            radius_km=radius_km,
            limit=limit,
        )
        return {
            "success": True,
            "query": {
                "latitude": latitude,
                "longitude": longitude,
                "year": year,
                "radius_km": radius_km,
            },
            "count": len(events),
            "events": [format_event_digest(e) for e in events],
            "sources": list(set(e.get("source", "curated") for e in events)),
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e),
        }

# ==========================
# Launch
# ==========================

def find_available_port(start_port=7860, max_attempts=10):
    """Find an available port starting from start_port"""
    import socket
    for i in range(max_attempts):
        port = start_port + i
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.bind(('0.0.0.0', port))
            sock.close()
            return port
        except OSError:
            sock.close()
            continue
    return None  # Fall back to Gradio's auto port selection

if __name__ == "__main__":
    app = create_app()
    # Hugging Face Spaces handles port automatically
    # Disable SSR to avoid Node.js server issues
    port = os.getenv("GRADIO_SERVER_PORT")
    if port:
        try:
            port = int(port)
            app.launch(server_name="0.0.0.0", server_port=port, share=False, ssr_mode=False)
        except ValueError:
            app.launch(server_name="0.0.0.0", share=False, ssr_mode=False)
    else:
        # Hugging Face Spaces - let Gradio handle everything automatically
        app.launch(ssr_mode=False)