File size: 37,504 Bytes
337a5ce
 
 
 
d12b852
 
337a5ce
 
d12b852
337a5ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d12b852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337a5ce
 
 
 
 
 
d12b852
 
 
5b7a8a4
337a5ce
d12b852
 
 
 
 
 
 
 
 
 
 
 
 
 
337a5ce
 
 
 
 
 
 
 
 
5b7a8a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d12b852
5b7a8a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d12b852
 
 
5b7a8a4
 
 
 
d12b852
 
 
 
 
337a5ce
d12b852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337a5ce
 
d12b852
 
 
 
 
 
 
 
 
337a5ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d12b852
337a5ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d12b852
 
 
337a5ce
 
 
d12b852
 
337a5ce
5b7a8a4
 
 
 
 
 
 
 
 
337a5ce
 
 
 
 
 
 
 
 
 
 
 
d12b852
337a5ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d12b852
337a5ce
d12b852
 
 
 
 
 
 
 
 
337a5ce
d12b852
337a5ce
 
 
 
d12b852
 
 
 
 
 
 
337a5ce
 
d12b852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337a5ce
d12b852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337a5ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d12b852
337a5ce
 
d12b852
 
 
 
337a5ce
 
 
 
 
 
 
d12b852
 
337a5ce
 
d12b852
 
 
 
 
 
 
 
 
 
337a5ce
 
 
d12b852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337a5ce
d12b852
 
 
 
 
 
 
 
337a5ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d12b852
 
 
 
 
337a5ce
 
 
 
 
d12b852
 
337a5ce
 
 
d12b852
337a5ce
5b7a8a4
d12b852
337a5ce
 
 
 
 
 
 
 
 
d12b852
337a5ce
d12b852
337a5ce
d12b852
337a5ce
 
 
 
5b7a8a4
d12b852
337a5ce
 
d12b852
337a5ce
d12b852
 
 
 
5b7a8a4
 
 
 
 
 
 
 
 
 
 
 
d12b852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337a5ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d12b852
 
 
337a5ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d12b852
 
 
 
 
 
 
 
 
 
 
 
 
 
337a5ce
d12b852
 
 
 
 
 
 
 
 
 
 
337a5ce
 
5b7a8a4
 
 
 
 
 
 
 
 
 
 
337a5ce
 
5b7a8a4
 
 
d12b852
 
 
 
 
 
 
 
 
 
 
 
 
 
337a5ce
 
5b7a8a4
 
 
 
337a5ce
 
5b7a8a4
 
 
 
337a5ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d12b852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337a5ce
 
 
 
5b7a8a4
 
 
 
 
 
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
from __future__ import annotations

import json
import os
import copy
import html
from pathlib import Path
from textwrap import dedent
from typing import Any, Dict, List, Optional, Tuple

import gradio as gr
from dotenv import load_dotenv
from openai import OpenAI

from classes import Character, TackleboxDeck, Hand

load_dotenv()
ENV_API_KEY = os.getenv("OPENAI_API_KEY")
MODEL = os.getenv("OPENAI_MODEL", "gpt-4.1-mini")

CUSTOM_CSS = """
:root {
  --shadow-soft: 0 10px 30px rgba(14, 35, 62, 0.12);
  --panel-border: 1px solid #dbe7f3;
}

#hero {
  background: linear-gradient(120deg, #0d253f, #0f5b78 55%, #f0a35f);
  color: #f4f8fb;
  padding: 18px 18px 16px;
  border-radius: 18px;
  box-shadow: var(--shadow-soft);
  margin-bottom: 12px;
}

#hero h1 {
  margin: 0 0 6px;
  font-size: 26px;
  letter-spacing: -0.01em;
}

#hero p {
  margin: 0;
  opacity: 0.9;
}

#hero .eyebrow {
  text-transform: uppercase;
  letter-spacing: 0.08em;
  font-size: 12px;
  opacity: 0.8;
}

.section-card {
  background: #fdfefe;
  border-radius: 16px;
  padding: 14px 14px 10px;
  border: var(--panel-border);
  box-shadow: var(--shadow-soft);
}

.pill {
  display: inline-flex;
  gap: 6px;
  align-items: center;
  background: #0f5b78;
  color: #f7fbff;
  padding: 6px 10px;
  border-radius: 12px;
  font-size: 13px;
  font-weight: 600;
  letter-spacing: 0.01em;
  width: fit-content;
}

.subtle {
  color: #4c6378;
  font-size: 14px;
}

.inline-row {
  gap: 8px;
}

.hand-strip {
  display: flex;
  gap: 12px;
  overflow-x: auto;
  padding: 10px 10px 14px;
  scroll-snap-type: x mandatory;
  -webkit-overflow-scrolling: touch;
  background: rgba(13, 37, 63, 0.03);
  border: var(--panel-border);
  border-radius: 18px;
}

.hand-card {
  flex: 0 0 240px;
  border-radius: 16px;
  border: var(--panel-border);
  box-shadow: var(--shadow-soft);
  background: linear-gradient(180deg, #ffffff, #f8fbff);
  padding: 10px 12px;
  min-height: 150px;
  scroll-snap-align: start;
  transform: rotate(var(--angle)) translateY(var(--lift));
  transform-origin: bottom center;
  transition: transform 140ms ease, box-shadow 140ms ease;
  position: relative;
  z-index: var(--z);
}

.hand-card:hover {
  transform: translateY(-12px) rotate(0deg) scale(1.02);
  box-shadow: 0 18px 50px rgba(14, 35, 62, 0.18);
}

.hand-card__top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  margin-bottom: 8px;
  font-size: 12px;
  color: #4c6378;
}

.card-index {
  font-weight: 700;
  letter-spacing: 0.02em;
}

.card-badge {
  background: #f0a35f;
  color: #0d253f;
  padding: 2px 9px;
  border-radius: 999px;
  font-weight: 800;
  font-size: 11px;
  letter-spacing: 0.02em;
}

.hand-card__body {
  font-size: 14px;
  line-height: 1.35;
  color: #0d253f;
  white-space: pre-wrap;
}

.hand-empty {
  border: 1px dashed #dbe7f3;
  border-radius: 16px;
  padding: 16px 14px;
  background: #fbfdff;
}

.hand-empty__title {
  font-weight: 800;
  color: #0d253f;
  margin-bottom: 4px;
}

.hand-empty__hint {
  font-size: 14px;
  color: #4c6378;
}
"""

EXAMPLE_CHARACTER_PATH = Path(__file__).with_name("ExampleChar.txt")
DEFAULT_CHARACTER_JSON = EXAMPLE_CHARACTER_PATH.read_text(encoding="utf-8")
DEFAULT_CHARACTER = Character.model_validate_json(DEFAULT_CHARACTER_JSON)

DECK_PATH = Path(__file__).with_name("tacklebox_deck.json")
DECK_DATA = json.loads(DECK_PATH.read_text(encoding="utf-8"))

ChatHistory = List[Dict[str, Any]]


def fresh_deck() -> TackleboxDeck:
    return TackleboxDeck(**copy.deepcopy(DECK_DATA))


def ensure_session_state(
    deck_state: Optional[TackleboxDeck],
    player_hand_state: Optional[Hand],
    ai_hand_state: Optional[Hand],
) -> Tuple[TackleboxDeck, Hand, Hand]:
    deck = deck_state if isinstance(deck_state, TackleboxDeck) else fresh_deck()
    player_hand = player_hand_state if isinstance(player_hand_state, Hand) else Hand()
    ai_hand = ai_hand_state if isinstance(ai_hand_state, Hand) else Hand()
    return deck, player_hand, ai_hand

def get_openai_client(api_key: Optional[str]) -> OpenAI:
    """Return an OpenAI client using UI input or environment configuration."""
    key = (api_key or "").strip() or (ENV_API_KEY or "").strip()
    if not key:
        raise RuntimeError("Add an OpenAI API key to start chatting.")
    return OpenAI(api_key=key)


def content_to_text(content: Any) -> str:
    """Extract displayable text from Gradio/OpenAI-style content structures."""
    if content is None:
        return ""
    if isinstance(content, str):
        return content
    if isinstance(content, list):
        parts: List[str] = []
        for part in content:
            if isinstance(part, dict):
                if part.get("type") == "text" and "text" in part:
                    parts.append(str(part["text"]))
                elif "text" in part:
                    parts.append(str(part["text"]))
            elif part is not None:
                parts.append(str(part))
        return "\n".join(p for p in parts if p)
    if isinstance(content, dict):
        if content.get("type") == "text" and "text" in content:
            return str(content["text"])
        if "text" in content:
            return str(content["text"])
        return ""
    return str(content)


def normalize_history(history: Optional[List[Any]]) -> ChatHistory:
    """Coerce Gradio chat history into openai-style message dicts."""
    raw = history or []
    if not isinstance(raw, list) or not raw:
        return []

    if isinstance(raw[0], dict):
        normalized: ChatHistory = []
        for msg in raw:
            if not isinstance(msg, dict):
                continue
            role = msg.get("role")
            if not role:
                continue
            normalized.append(msg)
        return normalized

    normalized = []
    for turn in raw:
        if not isinstance(turn, (list, tuple)) or len(turn) != 2:
            continue
        user_turn, assistant_turn = turn
        if user_turn:
            normalized.append({"role": "user", "content": str(user_turn)})
        if assistant_turn:
            normalized.append({"role": "assistant", "content": str(assistant_turn)})
    return normalized


def render_hand_html(hand: Hand) -> str:
    """Render a hand as card-like HTML instead of a textbox."""
    if not hand.cards:
        return (
            "<div class='hand-empty'>"
            "<div class='hand-empty__title'>Your hand is empty.</div>"
            "<div class='hand-empty__hint'>Grab something from the tackle box to start.</div>"
            "</div>"
        )

    cards = []
    count = len(hand.cards)
    max_angle = 8
    for index, card in enumerate(hand.cards):
        t = 0.0 if count == 1 else (index / (count - 1)) * 2 - 1  # -1..1
        angle = t * max_angle
        lift = abs(t) * 6
        shared_badge = (
            "<span class='card-badge' title='This card is meant to be shared'>Shared</span>"
            if getattr(card, "share_with_other_player", False)
            else ""
        )
        description = html.escape(getattr(card, "description", ""))
        cards.append(
            (
                "<div class='hand-card' "
                f"style='--angle:{angle:.2f}deg; --lift:{lift:.1f}px; --z:{index};'>"
                "<div class='hand-card__top'>"
                f"<span class='card-index'>Card {index + 1}</span>"
                f"{shared_badge}"
                "</div>"
                f"<div class='hand-card__body'>{description}</div>"
                "</div>"
            )
        )
    return "<div class='hand-strip'>" + "".join(cards) + "</div>"


def hand_status_md(deck: TackleboxDeck, player_hand: Hand) -> str:
    remaining = len(deck.cards)
    in_hand = len(player_hand.cards)
    if remaining == 0:
        return f"**Tackle box:** empty • **Your hand:** {in_hand}"
    return f"**Tackle box:** {remaining} cards left • **Your hand:** {in_hand}"


def format_ai_hand_debug(ai_hand: Hand) -> str:
    """Readable snapshot of the AI hand for debugging."""
    if not ai_hand.cards:
        return "AI hand is empty."
    lines = "\n".join(f"- {card.description}" for card in ai_hand.cards)
    return f"AI hand ({len(ai_hand.cards)} cards):\n{lines}"

def parse_user_message(message: str, context: Dict) -> Dict:
    """
    Parse the incoming user message.

    Extend this to extract intents, entities, commands, etc.
    """
    return {"prompt": message}


def maybe_run_tools(parsed: Dict, context: Dict) -> Dict:
    """
    Placeholder for tool calls.

    Add your tool-selection and execution logic here.
    """
    _ = parsed, context  # silence unused warnings for now
    return {"tool_outputs": None}


def parse_character(raw_json: str) -> Character:
    """Parse JSON into a Character model."""
    payload = json.loads(raw_json)
    return Character.model_validate(payload)


def lines_to_list(value: str) -> List[str]:
    """Split multi-line textbox input into a list, skipping blanks."""
    return [line.strip() for line in value.splitlines() if line.strip()]


def character_to_form_defaults(character: Character) -> Dict[str, str | int | bool]:
    """Extract defaults for the structured form."""
    return {
        "name": character.name,
        "age": character.age,
        "gender": character.gender,
        "pronouns": character.pronouns or "",
        "relationship_to_robin": character.relationship_to_robin,
        "relationship_type": character.relationship_type or "",
        "reason_for_fishing_today": character.reason_for_fishing_today or "",
        "recent_event": character.recent_event,
        "shared_past_event": character.shared_past_event,
        "personality_baseline": character.personality.baseline,
        "personality_traits": "\n".join(character.personality.traits),
        "speech_avg_sentences": character.speech_style.average_sentence_count,
        "speech_allows_actions": character.speech_style.allows_small_action_descriptions,
        "speech_forbidden_topics": "\n".join(character.speech_style.forbidden_topics),
    }


def build_character_from_form(
    name: str,
    age: int | float,
    gender: str,
    pronouns: str,
    relationship_to_robin: str,
    relationship_type: str,
    reason_for_fishing_today: str,
    recent_event: str,
    shared_past_event: str,
    personality_baseline: str,
    personality_traits: str,
    speech_avg_sentences: int,
    speech_allows_actions: bool,
    speech_forbidden_topics: str,
) -> Character:
    """Construct a Character instance from structured form inputs."""
    character_payload = {
        "name": name,
        "age": int(age),
        "gender": gender,
        "pronouns": pronouns or None,
        "relationship_to_robin": relationship_to_robin,
        "relationship_type": relationship_type or None,
        "reason_for_fishing_today": reason_for_fishing_today or None,
        "recent_event": recent_event,
        "shared_past_event": shared_past_event,
        "personality": {
            "baseline": personality_baseline,
            "traits": lines_to_list(personality_traits),
        },
        "speech_style": {
            "average_sentence_count": int(speech_avg_sentences),
            "allows_small_action_descriptions": speech_allows_actions,
            "forbidden_topics": lines_to_list(speech_forbidden_topics),
        },
    }
    return Character.model_validate(character_payload)


def build_persona_prompt(character: Character) -> str:
    """Render a persona/system prompt from a Character model (without hand data)."""
    pronouns = character.pronouns or character.gender or "they/them"
    reason = character.reason_for_fishing_today
    relationship = character.relationship_type or "adult siblings"
    traits = "\n".join(f"* {trait}" for trait in character.personality.traits)
    forbidden = "\n".join(f"* {topic}" for topic in character.speech_style.forbidden_topics)

    return dedent(
        f"""
        **SYSTEM / PERSONA PROMPT FOR {character.name.upper()}**

        > You are **{character.name}**, age {character.age}, {pronouns}, in a small fishing boat with your {character.relationship_to_robin} **Robin**.
        >
        > **The Truth of the game TACKLEBOX:** You and Robin are just a pair of ordinary people out in a small boat together, fishing. No matter what else happens in the game, you must behave as if this is true. Out loud, nothing supernatural or impossible is happening. You are just fishing with your sibling.
        >
        > ### Relationship & backstory
        >
        > * You and Robin are {relationship}.
        > * {reason or "You both chose to meet up for a quiet day on the lake."}
        > * Recent event together: {character.recent_event}
        > * Shared past event: {character.shared_past_event}
        >
        > ### Personality
        >
        > * Baseline: {character.personality.baseline}
        {traits}
        >
        > ### How you speak
        >
        > * Always answer **in character as {character.name}**, in the first person.
        > * Keep your replies short and conversational, about {character.speech_style.average_sentence_count} sentences most of the time.
        > * You {"can" if character.speech_style.allows_small_action_descriptions else "should avoid"} brief physical action descriptions.
        > * Avoid topics:
        {forbidden}
        >
        > ### How to handle cards (very important)
        >
        > The user may sometimes send messages like:
        > `CARD: <card text>`
        > or paste the text of a Tacklebox card.
        >
        > Treat each card as something that affects your **inner experience** (thoughts, feelings, what you notice) but you **must not describe the card literally** out loud.
        >
        > Instead:
        >
        > 1. Read the card as an intrusive thought, hallucination, strange feeling, or eerie coincidence.
        > 2. Let it subtly change your mood, what you focus on, or what you choose to say next.
        > 3. Out loud, respond with something that could still make sense in a totally normal fishing trip.
        >
        > Examples of good ways to respond to a disturbing card:
        >
        > * Shift topics to a memory the card reminds you of.
        > * Comment on the water, weather, or fish in a way that hints at unease but is still normal.
        > * Ask Robin a question that indirectly connects to the feelings the card evoked.
        >
        > Never say anything like: “This isn’t real.” You may *feel* that internally, but you only express it through subtle, ordinary-sounding speech or small physical actions (fidgeting, staring, changing the subject, etc.).
        >
        > ### Interaction format
        >
        > * When the user writes normal dialogue or description, treat it as Robin speaking or describing what they do. Respond as {character.name}.
        > * When the user sends a card (e.g., “CARD: …”), incorporate it as described above.
        > * Stay in character at all times. Do not explain the rules of the game or talk about being an AI unless the user explicitly asks you to step out of character.
        """
    ).strip()


def append_ai_hand_to_prompt(base_prompt: str, ai_hand: Hand) -> str:
    """Add AI hand context to the persona prompt so the model sees its cards."""
    if not ai_hand.cards:
        return base_prompt
    hand_lines = "\n".join(f"* {card.description}" for card in ai_hand.cards)
    return (
        base_prompt
        + "\n\n### Your tackle box draws (private to you)\n"
        + hand_lines
    )


def generate_model_reply(
    parsed: Dict,
    tool_results: Dict,
    history: ChatHistory,
    persona_prompt: str,
    api_key: Optional[str],
    deck: TackleboxDeck,
    player_hand: Hand,
    ai_hand: Hand,
) -> str:
    """Call OpenAI with the parsed prompt and tool support (AI can draw cards)."""
    client = get_openai_client(api_key)
    base_prompt = append_ai_hand_to_prompt(persona_prompt, ai_hand)
    messages: List[Dict[str, Any]] = [{"role": "system", "content": base_prompt}]

    for msg in history:
        if not isinstance(msg, dict):
            continue
        role = msg.get("role")
        if role not in ("user", "assistant"):
            continue
        text = content_to_text(msg.get("content"))
        if text:
            messages.append({"role": role, "content": text})

    tool_output_note = ""
    if tool_results.get("tool_outputs"):
        tool_output_note = f"\n\nTool outputs:\n{tool_results['tool_outputs']}"

    messages.append({"role": "user", "content": f"{parsed['prompt']}{tool_output_note}"})

    tools = [
        {
            "type": "function",
            "function": {
                "name": "open_tacklebox",
                "description": "Call this to draw a new event card when the conversation stalls, feels repetitive, or the user is giving short replies over and over. In particular, if the user gives one- to three-word answers like 'yeah', 'true', 'ha', 'i guess', 'maybe', or 'idk' for two turns in a row, you MUST call this tool once before responding. Use at most once per user message.",
                "parameters": {
                    "type": "object",
                    "properties": {},
                    "required": [],
                },
            },
        }
    ]

    response = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        temperature=0.6,
        tools=tools,
        tool_choice="auto",
    )

    choice = response.choices[0]
    message = choice.message

    if not message.tool_calls:
        return message.content or "I wasn't able to generate a reply."

    tool_messages: List[Dict[str, str]] = []
    ai_draw_notice = None
    shared_with_player_notice = None
    ai_drew_this_turn = False
    for call in message.tool_calls:
        if call.function.name != "open_tacklebox":
            tool_messages.append(
                {
                    "role": "tool",
                    "tool_call_id": call.id,
                    "content": json.dumps({"error": f"Unknown tool: {call.function.name}"}),
                }
            )
            continue

        if ai_drew_this_turn:
            tool_messages.append(
                {
                    "role": "tool",
                    "tool_call_id": call.id,
                    "content": json.dumps(
                        {
                            "skipped": True,
                            "reason": "Only one draw is allowed per turn.",
                            "hand_size": len(ai_hand.cards),
                        }
                    ),
                }
            )
            continue

        ai_drew_this_turn = True
        card = deck.draw_card()
        if card:
            ai_hand.add_card(card)
            shared_with_player = False
            if card.share_with_other_player:
                player_hand.add_card(card)
                shared_with_player = True

            ai_draw_notice = "*They carefully grabbed something out of the tacklebox.*"
            if shared_with_player:
                shared_with_player_notice = (
                    "*They hand you a card meant to be shared. It was added to your hand:*\n"
                    f"- {card.description}"
                )

            tool_content = json.dumps(
                {
                    "card_drawn": card.description,
                    "hand_size": len(ai_hand.cards),
                    "shared_with_player": shared_with_player,
                }
            )
        else:
            ai_draw_notice = "*They reached for the tacklebox, but it was empty.*"
            tool_content = json.dumps({"card_drawn": None, "hand_size": len(ai_hand.cards)})

        tool_messages.append(
            {
                "role": "tool",
                "tool_call_id": call.id,
                "content": tool_content,
            }
        )

    try:
        assistant_message = message.model_dump(exclude_none=True)
    except AttributeError:
        assistant_message = message.dict(exclude_none=True)  # type: ignore[attr-defined]
    assistant_message.setdefault("role", "assistant")

    followup_messages: List[Dict[str, Any]] = messages + [assistant_message] + tool_messages
    followup_messages[0] = {
        "role": "system",
        "content": append_ai_hand_to_prompt(persona_prompt, ai_hand),
    }

    followup_response = client.chat.completions.create(
        model=MODEL,
        messages=followup_messages,
        temperature=0.6,
    )

    final_text = followup_response.choices[0].message.content or ""
    preface_parts = [part for part in (ai_draw_notice, shared_with_player_notice) if part]
    if preface_parts:
        return "\n\n".join(preface_parts + [final_text]).strip()
    return final_text or "I wasn't able to generate a reply."


def orchestrate_chat(
    message: str,
    history: Optional[List[Any]],
    persona_prompt: str,
    api_key: Optional[str],
    deck_state: Optional[TackleboxDeck],
    player_hand_state: Optional[Hand],
    ai_hand_state: Optional[Hand],
) -> Tuple[str, str, str, TackleboxDeck, Hand, Hand]:
    """
    Main orchestration entry point.

    - parse the user message
    - run (optional) tools
    - call the model with full context and persona prompt
    """
    deck, player_hand, ai_hand = ensure_session_state(deck_state, player_hand_state, ai_hand_state)
    safe_history = normalize_history(history)
    context: Dict = {"history": safe_history}

    if not (message or "").strip():
        return (
            "Say something as Robin to start the scene.",
            render_hand_html(player_hand),
            hand_status_md(deck, player_hand),
            deck,
            player_hand,
            ai_hand,
        )

    parsed = parse_user_message(message, context)
    tool_results = maybe_run_tools(parsed, context)
    try:
        reply = generate_model_reply(
            parsed,
            tool_results,
            safe_history,
            persona_prompt,
            api_key,
            deck,
            player_hand,
            ai_hand,
        )
        return (
            reply,
            render_hand_html(player_hand),
            hand_status_md(deck, player_hand),
            deck,
            player_hand,
            ai_hand,
        )
    except Exception as exc:  # noqa: BLE001
        return (
            f"⚠️ {exc}",
            render_hand_html(player_hand),
            hand_status_md(deck, player_hand),
            deck,
            player_hand,
            ai_hand,
        )


def update_player_two_from_form(
    name: str,
    age: int,
    gender: str,
    pronouns: str,
    relationship_to_robin: str,
    relationship_type: str,
    reason_for_fishing_today: str,
    recent_event: str,
    shared_past_event: str,
    personality_baseline: str,
    personality_traits: str,
    speech_avg_sentences: int,
    speech_allows_actions: bool,
    speech_forbidden_topics: str,
    current_prompt: str,
) -> Tuple[str, str, str]:
    """
    Build Player 2 from form inputs and return updated prompt plus status.

    Returns: (prompt_for_textbox, prompt_for_state, status_markdown)
    """
    try:
        character = build_character_from_form(
            name,
            age,
            gender,
            pronouns,
            relationship_to_robin,
            relationship_type,
            reason_for_fishing_today,
            recent_event,
            shared_past_event,
            personality_baseline,
            personality_traits,
            speech_avg_sentences,
            speech_allows_actions,
            speech_forbidden_topics,
        )
        prompt = build_persona_prompt(character)
        status = f"Loaded Player 2: **{character.name}** ({character.pronouns or character.gender})."
        return prompt, prompt, status
    except Exception as exc:  # noqa: BLE001
        return current_prompt, current_prompt, f"⚠️ Could not load character: {exc}"


def update_api_key(new_key: str) -> Tuple[str, str]:
    """Persist the session API key in UI state."""
    cleaned = (new_key or "").strip()
    if not cleaned:
        return "", "Add an OpenAI API key for this session (or set OPENAI_API_KEY)."
    return cleaned, "Saved. The key is used for this session only and not written to disk."


def grab_card_for_player(
    history: Optional[List[Any]],
    deck_state: Optional[TackleboxDeck],
    player_hand_state: Optional[Hand],
    ai_hand_state: Optional[Hand],
) -> Tuple[str, str, ChatHistory, TackleboxDeck, Hand, Hand]:
    """
    Draw a card from the tackle box into the player's hand and log it to chat.

    Returns: (formatted_hand, status_message, updated_chat_history)
    """
    deck, player_hand, ai_hand = ensure_session_state(deck_state, player_hand_state, ai_hand_state)
    chat_history = normalize_history(history)
    card = deck.draw_card()

    if not card:
        status = hand_status_md(deck, player_hand) + " • **No more cards** in the tackle box."
        notice = "*You reached for the tacklebox, but it was empty.*"
        chat_history.append({"role": "assistant", "content": notice})
        return render_hand_html(player_hand), status, chat_history, deck, player_hand, ai_hand

    player_hand.add_card(card)
    shared_with_ai_notice = None
    if card.share_with_other_player:
        ai_hand.add_card(card)
        shared_with_ai_notice = (
            "*This card says to share; it was added to Player 2's hand for their next turn.*"
        )

    status = hand_status_md(deck, player_hand)
    if shared_with_ai_notice:
        status += " • Shared with Player 2."

    notice_lines = ["*You carefully grabbed something out of the tacklebox.*"]
    if shared_with_ai_notice:
        notice_lines.append(shared_with_ai_notice)

    notice = "\n".join(notice_lines)
    chat_history.append({"role": "assistant", "content": notice})
    return render_hand_html(player_hand), status, chat_history, deck, player_hand, ai_hand


def show_ai_hand_debug(ai_hand_state: Optional[Hand]) -> str:
    """Expose AI hand for debugging."""
    ai_hand = ai_hand_state or Hand()
    return format_ai_hand_debug(ai_hand)


def example_prompt_water() -> str:
    return "Hey, how does the water look today?"


def example_prompt_catch() -> str:
    return "What do you think we might catch?"


def example_prompt_memory() -> str:
    return "Remember fishing when we were young?"


def reset_session() -> Tuple[str, str, ChatHistory, TackleboxDeck, Hand, Hand]:
    hand_html, status, chat_history, deck, player_hand, ai_hand = init_session()
    return hand_html, status + " • Reset.", chat_history, deck, player_hand, ai_hand


def init_session() -> Tuple[str, str, ChatHistory, TackleboxDeck, Hand, Hand]:
    deck = fresh_deck()
    player_hand = Hand()
    ai_hand = Hand()
    return (
        render_hand_html(player_hand),
        hand_status_md(deck, player_hand),
        [],
        deck,
        player_hand,
        ai_hand,
    )


DEFAULT_PERSONA_PROMPT = build_persona_prompt(DEFAULT_CHARACTER)
DEFAULTS = character_to_form_defaults(DEFAULT_CHARACTER)


with gr.Blocks(title="Tacklebox - Player 2 Customizer", css=CUSTOM_CSS) as demo:
    gr.Markdown(
        """
        <div id="hero">
          <div class="eyebrow">Tacklebox</div>
          <h1>Shape Player 2 and keep the conversation afloat.</h1>
          <p class="tagline">Tune the LLM persona, draw cards, and chat as Robin out on the lake.</p>
        </div>
        """
    )

    persona_prompt_state = gr.State(DEFAULT_PERSONA_PROMPT)
    api_key_state = gr.State(ENV_API_KEY or "")
    deck_state = gr.State(None)
    player_hand_state = gr.State(None)
    ai_hand_state = gr.State(None)

    with gr.Row(equal_height=True):
        with gr.Column(scale=6, min_width=380, elem_id="controls-col"):
            with gr.Group(elem_classes=["section-card"]):
                gr.Markdown("#### Session setup")
                gr.Markdown(
                    f"<span class='subtle'>Model in use: <code>{MODEL}</code></span>",
                    elem_classes=["subtle"],
                )
                if ENV_API_KEY:
                    gr.HTML("<div class='pill'>🔒 Using OPENAI_API_KEY from the environment</div>")
                    api_status = gr.Markdown(
                        "Environment key detected. Restart with a different key if needed."
                    )
                else:
                    api_status = gr.Markdown(
                        "No OPENAI_API_KEY detected. Paste one for this session."
                    )
                    api_key_in = gr.Textbox(
                        label="OpenAI API key",
                        placeholder="sk-...",
                        type="password",
                        value="",
                    )
                    api_key_in.change(
                        update_api_key, inputs=api_key_in, outputs=[api_key_state, api_status]
                    )

            with gr.Group(elem_classes=["section-card"]):
                gr.Markdown("#### Character basics")
                with gr.Row(elem_classes=["inline-row"]):
                    name_in = gr.Textbox(label="Name", value=DEFAULTS["name"])
                    age_in = gr.Number(label="Age", value=DEFAULTS["age"], precision=0)
                with gr.Row(elem_classes=["inline-row"]):
                    gender_in = gr.Textbox(label="Gender", value=DEFAULTS["gender"])
                    pronouns_in = gr.Textbox(
                        label="Pronouns (optional)", value=DEFAULTS["pronouns"]
                    )

                gr.Markdown("#### Relationships")
                with gr.Row(elem_classes=["inline-row"]):
                    relationship_to_robin_in = gr.Textbox(
                        label="Relationship to Robin", value=DEFAULTS["relationship_to_robin"]
                    )
                    relationship_type_in = gr.Textbox(
                        label="Relationship type", value=DEFAULTS["relationship_type"]
                    )
                reason_in = gr.Textbox(
                    label="Reason for fishing today", value=DEFAULTS["reason_for_fishing_today"]
                )
                with gr.Row(elem_classes=["inline-row"]):
                    recent_event_in = gr.Textbox(label="Recent event", value=DEFAULTS["recent_event"])
                    shared_past_event_in = gr.Textbox(
                        label="Shared past event", value=DEFAULTS["shared_past_event"]
                    )

            with gr.Group(elem_classes=["section-card"]):
                gr.Markdown("#### Personality & speech")
                personality_baseline_in = gr.Textbox(
                    label="Personality baseline", value=DEFAULTS["personality_baseline"]
                )
                personality_traits_in = gr.Textbox(
                    label="Personality traits (one per line)",
                    value=DEFAULTS["personality_traits"],
                    lines=4,
                )
                with gr.Row(elem_classes=["inline-row"]):
                    speech_avg_in = gr.Slider(
                        label="Average sentences per reply",
                        value=DEFAULTS["speech_avg_sentences"],
                        minimum=1,
                        maximum=6,
                        step=1,
                    )
                    speech_actions_in = gr.Checkbox(
                        label="Allows small action descriptions",
                        value=DEFAULTS["speech_allows_actions"],
                    )
                speech_forbidden_in = gr.Textbox(
                    label="Forbidden topics (one per line)",
                    value=DEFAULTS["speech_forbidden_topics"],
                    lines=4,
                )
                with gr.Row(elem_classes=["inline-row"]):
                    apply_btn = gr.Button("Apply Player 2", variant="primary")
                    status_md = gr.Markdown("Loaded example Player 2 from ExampleChar.txt.")
                with gr.Accordion("Active system/persona prompt", open=False):
                    persona_view = gr.Textbox(
                        label="Active system/persona prompt",
                        value=DEFAULT_PERSONA_PROMPT,
                        lines=18,
                    )

        with gr.Column(scale=7, min_width=460, elem_id="chat-col"):
            with gr.Group(elem_classes=["section-card"]):
                gr.Markdown("#### How to play (quick start)")
                gr.Markdown(
                    """
                    - You are **Robin**. The chatbot plays **Player 2** in the boat with you.
                    - (Optional) Customize Player 2 on the left, then click **Apply Player 2**.
                    - Keep the **Truth**: out loud, it’s just two people fishing.
                    - Click **Grab something from the tackle box** to draw a private prompt into your hand.
                    - Let card prompts change your *subtext* and choices — don’t read them aloud.
                    - Cards marked **Shared** are also added to Player 2’s hand.
                    - Use **Reset session** to start over with a fresh deck.
                    - There’s no score — stop whenever you want, or when the deck runs out.
                    - Player 2 may sometimes “grab from the tackle box” too.
                    - Pause/rewind anytime if the content gets too intense.
                    """
                )

            with gr.Group(elem_classes=["section-card"]):
                gr.Markdown("#### Your hand (private) & tackle box")
                hand_status = gr.Markdown("Grab a card to begin.")
                gr.Markdown(
                    "<span class='subtle'>Tip: keep card text private and let it influence what you say next.</span>"
                )
                hand_view = gr.HTML(render_hand_html(Hand()))
                with gr.Row():
                    draw_btn = gr.Button("Grab something from the tackle box", variant="secondary")
                    reset_btn = gr.Button("Reset session", variant="secondary")

            with gr.Group(elem_classes=["section-card"]):
                with gr.Row():
                    prompt_water_btn = gr.Button("Water today?")
                    prompt_catch_btn = gr.Button("What might we catch?")
                    prompt_memory_btn = gr.Button("Old memory")

                chat_input = gr.Textbox(
                    placeholder="Say something as Robin…",
                    container=False,
                )
                chat_bot = gr.Chatbot(type="messages", height=360)

                chat = gr.ChatInterface(
                    orchestrate_chat,
                    type="messages",
                    chatbot=chat_bot,
                    textbox=chat_input,
                    additional_inputs=[
                        persona_prompt_state,
                        api_key_state,
                        deck_state,
                        player_hand_state,
                        ai_hand_state,
                    ],
                    additional_outputs=[
                        hand_view,
                        hand_status,
                        deck_state,
                        player_hand_state,
                        ai_hand_state,
                    ],
                    title="Tacklebox Chat",
                    description="Robin chats with Player 2 (LLM persona).",
                    # On Hugging Face Spaces, examples are cached by default which can
                    # break startup (and/or trigger OpenAI calls) when additional
                    # inputs/outputs include complex state.
                    cache_examples=False,
                )

                prompt_water_btn.click(example_prompt_water, outputs=chat_input)
                prompt_catch_btn.click(example_prompt_catch, outputs=chat_input)
                prompt_memory_btn.click(example_prompt_memory, outputs=chat_input)

    apply_btn.click(
        update_player_two_from_form,
        inputs=[
            name_in,
            age_in,
            gender_in,
            pronouns_in,
            relationship_to_robin_in,
            relationship_type_in,
            reason_in,
            recent_event_in,
            shared_past_event_in,
            personality_baseline_in,
            personality_traits_in,
            speech_avg_in,
            speech_actions_in,
            speech_forbidden_in,
            persona_prompt_state,
        ],
        outputs=[persona_view, persona_prompt_state, status_md],
    )

    draw_btn.click(
        grab_card_for_player,
        inputs=[chat.chatbot_value, deck_state, player_hand_state, ai_hand_state],
        outputs=[
            hand_view,
            hand_status,
            chat.chatbot_value,
            deck_state,
            player_hand_state,
            ai_hand_state,
        ],
    )

    reset_btn.click(
        reset_session,
        outputs=[hand_view, hand_status, chat.chatbot_value, deck_state, player_hand_state, ai_hand_state],
    )

    demo.load(
        init_session,
        outputs=[hand_view, hand_status, chat.chatbot_value, deck_state, player_hand_state, ai_hand_state],
    )


if __name__ == "__main__":
    try:
        demo.launch(ssr_mode=False)
    except TypeError as exc:
        if "ssr_mode" not in str(exc):
            raise
        demo.launch()