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42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
"""Interview screen — build the profile by conversation instead of by files.

A user with no dossier folder (or a thin one) answers a guided set of
questions here and ends up with the same profile evidence the folder path
produces. The screen owns the conversation only: the question bank, the
answer validation, the follow-ups and the evidence build all live in
:mod:`app.services.interview`.

Answers are stored exactly as the user typed them: nothing here rewrites,
tidies or "cleans" what they wrote. The AI earns its place on the
conversation instead — checking an answer fits the question that was asked,
asking a follow-up when a needed detail is missing, phrasing the next
question, and acknowledging what was said.

On completion this writes exactly the session state a dossier read writes —
``dossier_chunks``, ``dossier_read``, ``dossier_read_error``,
``evidence_index``, ``canonical_profile``, ``evidence_index_meta`` — so every
screen downstream of Dossier works unchanged, plus ``profile_source`` so the
rest of the app can tell the two paths apart.

The interview is a second way through the Dossier step rather than a step of
its own: it renders under the Dossier rail row and the Dossier step number
(see ``STEP_PARENT`` in ``app/main.py``).

Nothing here is imported at provider level: the screen renders a clean
message and stays out of the way if the interview service is unavailable.
"""

from __future__ import annotations

import traceback
import copy
import re
from types import SimpleNamespace
from typing import Any

import streamlit as st

from app.config import clear_opportunity_state, get_settings
from app.services.evidence_index import build_evidence_index
from app.ui import theme
from app.utils.logging_utils import get_logger

_logger = get_logger("upwork_strategist.interview_screen")

try:  # The interview service is a separate module; a missing or broken
    # import must never take the rest of the app down with it.
    from app.services import interview
except Exception:  # noqa: BLE001 - the screen degrades to a clean message
    interview = None  # type: ignore[assignment]


# ---------------------------------------------------------------------------
# Session keys
# ---------------------------------------------------------------------------
#
# The first three are the contract keys other screens read. The last two are
# display-only state owned by this screen: the latest turn's reply, and a
# counter that forms part of the answer box's widget key so the box re-mounts
# empty after every send (the widget-reset idiom used elsewhere in this app).

_STATE_KEY = "interview_state"
_STARTED_KEY = "interview_started"
_SOURCE_KEY = "profile_source"
_LAST_TURN_KEY = "interview_last_turn"
_SEQ_KEY = "interview_turn_seq"

# The AI toggle's value, kept outside the widget. The intro card is not drawn
# while the interview runs, so Streamlit collects the toggle's own key, and a
# toggle seeded from ``value=`` alone springs back to its default the next
# time the card is drawn — silently overriding a choice the user made on
# purpose. This key is a plain value and survives that gap.
_AI_CHOICE_KEY = "interview_ai_choice"
_AI_TOGGLE_KEY = "interview_ai_toggle"

# Set when a Groq key is accepted on this screen. Streamlit keeps a widget's
# last value and ignores a new ``value=``, so without this the toggle would
# stay off — drawn disabled while there was no key — and the user who was
# just told "AI help is on" would start an interview without it.
_AI_FORCE_ON_KEY = "interview_ai_force_on"

# "Start over" throws away every answer given so far, so it asks first: this
# holds the "asked, not yet confirmed" step between the two clicks.
_RESTART_CONFIRM_KEY = "interview_restart_confirm"

# Below this many answered questions there is not enough to build a profile
# from, so "Finish early" stays disabled.
_MIN_ANSWERS_TO_FINISH = 3

# What a skip and a step backwards say. The skip line only tells the truth
# because "Previous" exists: without a way back there would be no "later".
_SKIP_ACK = "Skipped — you can come back to it with Previous."
_BACK_ACK = (
    "Back to the previous question. Your earlier answer is in the box: edit it "
    "and Send to replace it, or Skip to keep it."
)

# Which API the interview runs on this session: "" tries a Groq key first,
# "main" is set when the Groq check failed and the Setup API took over, and
# the note says so in words.
_ROUTE_PREF_KEY = "interview_route_pref"
_ROUTE_NOTE_KEY = "interview_route_note"

# How the user came in. "chooser" is "Interview me instead": the interview
# replaces any folder read earlier — unless the profile already carries this
# interview on top of that folder (see :func:`_joins_folder`). "gap_fill" is the
# thin-folder offer: the interview adds to the folder. Set by the dossier
# screen.
_ENTRY_KEY = "interview_entry"

# The longest answer the service stores. The box stops there with a visible
# counter, so nothing is ever cut without the user seeing it.
_MAX_ANSWER_CHARS = int(getattr(interview, "_MAX_ANSWER_CHARS", 1500) or 1500)

# Markdown punctuation. Model replies and typed answers are shown as text:
# a "$10 then $20" must not turn into maths, nor "*this*" into italics.
_MD_SPECIAL = re.compile(r"([\\`*_{}\[\]()#+\-.!|$<>~])")


def _plain(text: Any) -> str:
    """Escape Markdown so a dynamic message is shown exactly as written."""
    return _MD_SPECIAL.sub(r"\\\1", str(text or ""))

# How many transcript entries stay on screen. The whole conversation is kept
# in state; only the tail is rendered so the page stays readable.
_TRANSCRIPT_TAIL = 8

_BUILD_FAILED_MESSAGE = (
    "We couldn't turn those answers into a profile yet. Answer a few more "
    "questions and try again."
)

# The interview provider is checked once, on the way in, and the verdict is
# cached under this key: the screen reruns on every turn, and a live probe
# per turn would spend the user's free quota on diagnostics.
_API_CHECK_KEY = "interview_api_check"

# Where the interview publishes its own strength score. ``dossier_validation``
# describes a folder of files and is never written from here.
_STRENGTH_KEY = "interview_strength"

# Status strings from ``app.services.api_gate.ApiGateError``. Spelled out
# rather than imported so this module keeps importing with no gate present.
_STATUS_OK = "API OK"
_STATUS_INVALID_KEY = "INVALID API KEY"
_STATUS_QUOTA = "API QUOTA EXCEEDED"
_STATUS_NO_KEY = "NO API ADDED"
_STATUS_NO_MODEL = "MODEL NOT CONFIGURED"
_STATUS_CONNECTION = "API CONNECTION FAILED"

# What the user is told when the check comes back as anything but OK. They
# all end the same way, because none of them stops the interview.
_AI_OFF_REASONS: dict[str, str] = {
    "MODEL NOT ACCEPTED": "The provider rejected the interview model. Choose another model in Setup. The interview can continue without AI help.",
    "API ACCESS DENIED": "Your key cannot access the interview model. Check permissions or choose another model in Setup. The interview can continue without AI help.",
    _STATUS_INVALID_KEY: (
        "The API key the interview uses was rejected, so it asks its questions as "
        "written, with only basic answer checks and no follow-ups."
    ),
    _STATUS_QUOTA: (
        "The interview's API quota is used up for now, so it asks its "
        "questions as written, with only basic answer checks and no follow-ups."
    ),
    _STATUS_NO_KEY: (
        "No API key is available for the interview, so it asks its questions "
        "as written, with only basic answer checks and no follow-ups."
    ),
    _STATUS_NO_MODEL: (
        "No interview model is configured, so the interview asks its "
        "questions as written, with only basic answer checks and no follow-ups."
    ),
    _STATUS_CONNECTION: (
        "The interview service couldn't be reached, so it asks its questions "
        "as written, with only basic answer checks and no follow-ups."
    ),
}

_AI_OFF_FALLBACK = (
    "No AI service is set up for the interview, so it asks its questions as "
    "written, with only basic answer checks and no follow-ups."
)

# Said alongside every one of those: what the AI is off changes, and what it
# never changed.
_ANSWERS_VERBATIM = "Your answers are saved exactly as you type them either way."


# ---------------------------------------------------------------------------
# Availability
# ---------------------------------------------------------------------------


def is_available() -> bool:
    """True when the interview path can be offered to the user.

    The dossier screen asks before it advertises the interview, so a missing
    service simply leaves the existing folder flow exactly as it was.
    """
    return interview is not None


def show_intro_on_entry() -> None:
    """Send the next visit to the interview back to its intro card.

    ``interview_started`` is what hides that card, and nothing else clears
    it, so a user who left a part-finished interview and came back would
    land straight on the live question with the AI toggle and "Start over"
    out of reach. No answer is touched: with a state in hand the card's
    button reads "Resume the interview".
    """
    st.session_state[_STARTED_KEY] = False
    # A "Start over" that was asked but never confirmed on an earlier visit
    # must not be sitting there with its confirm button live.
    st.session_state[_RESTART_CONFIRM_KEY] = False


def _run_api_check(settings: Any, prefer: str = "") -> Any:
    """Probe the interview provider and return the gate's verdict.

    Imported lazily so this module stays importable with no provider set
    up. The probe is live because that is the only way to tell a rejected
    key from an exhausted free tier, and the two need different words.
    """
    try:
        from app.services.api_gate import run_interview_capability_test
    except Exception:  # noqa: BLE001 - older gate without the interview check
        return None
    kwargs: dict = {"settings": settings, "live": True}
    if prefer:
        kwargs["prefer"] = prefer
    try:
        with st.spinner("Checking the interview service…"):
            return run_interview_capability_test(**kwargs)
    except Exception:  # noqa: BLE001 - never let a probe break the screen
        return None


def _status_of(verdict: Any) -> str:
    return str(getattr(verdict, "status", "") or "")


def _routes(settings: Any) -> tuple[Any, Any]:
    """The default interview route, and the Setup API route without Groq."""
    try:
        from app.services import llm_client  # lazy: importable without it

        return (
            llm_client.interview_route(settings),
            llm_client.interview_route(settings, prefer="main"),
        )
    except Exception:  # noqa: BLE001 - a missing router means no routes
        return None, None


_FAILURE_WORDS = {
    _STATUS_INVALID_KEY: "the key was rejected",
    _STATUS_QUOTA: "its free quota is used up",
    _STATUS_NO_MODEL: "its model isn't available",
    _STATUS_CONNECTION: "it couldn't be reached",
}


def _probe(settings: Any) -> Any:
    """Check the interview's API, falling back from Groq to the Setup API.

    A Groq key wins when one is set, but when its check fails and the Setup
    API works, the interview runs on the Setup API instead of losing its AI
    — and the note says why. The choice is kept for the session.
    """
    st.session_state[_ROUTE_PREF_KEY] = ""
    st.session_state.pop(_ROUTE_NOTE_KEY, None)
    verdict = _run_api_check(settings)
    status = _status_of(verdict)
    if status == _STATUS_OK:
        return verdict
    default, main = _routes(settings)
    if default and main and default[0] == "groq" and main[0] != "groq":
        fallback = _run_api_check(settings, prefer="main")
        if _status_of(fallback) == _STATUS_OK:
            st.session_state[_ROUTE_PREF_KEY] = "main"
            name = _PROVIDER_NAMES.get(str(main[0]), str(main[0]).title())
            why = _FAILURE_WORDS.get(status, "it couldn't be used")
            st.session_state[_ROUTE_NOTE_KEY] = (
                f"Your Groq key couldn't be used ({why}), so the interview "
                f"uses your {name} API from Setup instead."
            )
            return fallback
    return verdict


def _checked() -> bool:
    """True once this session has a verdict — even an empty one — in hand.

    What separates "the AI is unavailable" from "nobody has looked yet". The
    intro card is drawn before anyone has looked, and must not start a
    network call just because the user opened it.
    """
    return _API_CHECK_KEY in st.session_state


def _api_check(settings: Any) -> Any:
    """This session's cached verdict, running the probe on first use.

    The key is written even when the probe returns nothing, so a provider
    that is down is asked exactly once per session and never again on the
    reruns that carry the conversation.
    """
    if _API_CHECK_KEY not in st.session_state:
        st.session_state[_API_CHECK_KEY] = _probe(settings)
    return st.session_state.get(_API_CHECK_KEY)


def _ai_status(settings: Any) -> str:
    return str(getattr(_api_check(settings), "status", "") or "")


def _ai_ready(settings: Any) -> bool:
    """True when the interview's AI turns can actually run."""
    return _ai_status(settings) == _STATUS_OK


def _cached_status() -> str:
    """The verdict already in hand, or "" — never starts a probe."""
    return str(getattr(st.session_state.get(_API_CHECK_KEY), "status", "") or "")


def _cached_ai_ready() -> bool:
    """True when a verdict is in hand and it says the AI turns can run."""
    return _cached_status() == _STATUS_OK


def _ai_off_reason() -> str:
    """Why the AI turns are off, in the user's words — "" when they are on.

    Reads the verdict already in hand: it is only ever asked for after
    something has looked.
    """
    status = _cached_status()
    if status == _STATUS_OK:
        return ""
    return f"{_AI_OFF_REASONS.get(status, _AI_OFF_FALLBACK)} {_ANSWERS_VERBATIM}"


# ---------------------------------------------------------------------------
# State
# ---------------------------------------------------------------------------


# ---------------------------------------------------------------------------
# Groq key, entered on this screen
# ---------------------------------------------------------------------------

# A one-shot (kind, text) message shown after a key is saved, because the
# save reruns the page and a message drawn before the rerun would be lost.
_KEY_FLASH_KEY = "interview_key_flash"


def _interview_key_env() -> str:
    """Env name holding the interview key, e.g. ``GROQ_API_KEY``."""
    provider = str(getattr(interview, "INTERVIEW_PROVIDER", "groq") or "groq")
    return f"{provider.strip().upper() or 'GROQ'}_API_KEY"


_PROVIDER_NAMES = {
    "anthropic": "Claude",
    "openai": "OpenAI",
    "groq": "Groq",
    "gemini": "Gemini",
}


def _route_name(settings: Any) -> tuple[str, bool]:
    """The interview's provider as the user knows it, and whether it is Setup's.

    Returns ``("", False)`` when no provider is available. The second value
    is True when the interview runs on the same API configured on Setup,
    False when a separately added Groq key has taken over.
    """
    pref = str(st.session_state.get(_ROUTE_PREF_KEY, "") or "")
    try:
        from app.services import llm_client  # lazy: importable without it

        route = (
            llm_client.interview_route(settings, prefer=pref)
            if pref
            else llm_client.interview_route(settings)
        )
    except Exception:  # noqa: BLE001 - a missing router means no provider
        route = None
    if not route:
        return "", False
    provider = str(route[0] or "")
    main = str(getattr(settings, "llm_provider", "") or "").strip().lower()
    return _PROVIDER_NAMES.get(provider, provider.title()), provider == main


def _has_interview_key(settings: Any) -> bool:
    try:
        return bool(interview.interview_available(settings))  # type: ignore[union-attr]
    except Exception:  # noqa: BLE001 - a missing helper means no key
        return False


def _key_is_main_key(settings: Any) -> bool:
    """True when the interview's key slot is the one the main API runs on.

    With Groq picked on Setup, a key typed on this screen would replace the
    key every other step uses, and a mistyped one would erase it. Setup
    hides its own interview-key field in this case for the same reason.
    """
    provider = str(getattr(interview, "INTERVIEW_PROVIDER", "groq") or "groq")
    main = str(getattr(settings, "llm_provider", "") or "")
    return main.strip().lower() == provider.strip().lower()


def _needs_key_form(settings: Any, state: Any) -> bool:
    """True when the AI can't run for want of a working key.

    Not shown when the AI is off for a reason a key can't fix — the user
    turned it off with a working key in hand, or this interview has used up
    its own call allowance.
    """
    if _cached_ai_ready():
        return False
    if state is not None:
        reason = str(getattr(state, "ai_off_reason", "") or "")
        if reason == getattr(interview, "AI_OFF_BUDGET", "budget_spent"):
            return False
    if _checked():
        return _cached_status() in (
            _STATUS_NO_KEY,
            _STATUS_INVALID_KEY,
            _STATUS_QUOTA,
            _STATUS_NO_MODEL,
            _STATUS_CONNECTION,
            "",
        )
    return not _has_interview_key(settings)


def _remember_config() -> None:
    """Remember the session's keys on this device, when storage is set up."""
    try:
        from app.ui import setup_screen  # lazy: avoids an import cycle

        setup_screen.remember_config()
    except Exception:  # noqa: BLE001 - remembering is a nicety, never a blocker
        pass


def _save_interview_key(raw: str, state: Any) -> None:
    """Apply a typed Groq key, test it live, and act on the verdict. Caller reruns.

    The key goes into this session's memory the same way the Setup screen
    puts it there, but the main API check is left alone: this key only ever
    gates the interview's AI turns, so saving it must not send the user
    back to Setup. It is remembered on the device only once Groq has
    answered for it: accepted, or out of quota.
    """
    from app import config  # lazy: keeps this module importable anywhere

    key = (raw or "").strip()
    if not key:
        st.session_state[_KEY_FLASH_KEY] = (
            "warning",
            "Paste your Groq key into the box first. It starts with gsk_.",
        )
        return

    env = _interview_key_env()
    # What the slot held before, so a rejected key can be undone rather than
    # leaving the session without a key it had.
    previous = str(config.export_session_overrides().get(env, "") or "")
    config.apply_session_overrides({env: key})
    st.session_state.pop(_API_CHECK_KEY, None)
    settings = get_settings()
    groq_verdict = _run_api_check(settings)
    groq_status = _status_of(groq_verdict)

    if groq_status == _STATUS_OK:
        _remember_config()
        st.session_state[_API_CHECK_KEY] = groq_verdict
        st.session_state[_ROUTE_PREF_KEY] = ""
        st.session_state.pop(_ROUTE_NOTE_KEY, None)
        _ai_back_on(state, route_pref="")
        st.session_state[_KEY_FLASH_KEY] = (
            "success",
            "Groq key accepted — AI help is on. It now checks each answer and "
            "asks a follow-up when something is missing.",
        )
        return

    if groq_status == _STATUS_INVALID_KEY:
        # A rejected key is not kept: leaving it would make the app believe a
        # key is set up when none works. The slot goes back to what it held,
        # so a mistyped paste never costs a key the session already had —
        # unless that was the key just rejected.
        config.apply_session_overrides({env: previous if previous != key else ""})
        settings = get_settings()
    elif groq_status == _STATUS_QUOTA:
        # Rate-limited: Groq answered for the key, so keep and remember it.
        _remember_config()
    # Unreachable or unanswered, the key may be fine, so it is kept — for
    # this session only, because nothing has confirmed it yet.

    # The Setup API can still carry the interview.
    verdict = _probe(settings)
    st.session_state[_API_CHECK_KEY] = verdict
    why = _FAILURE_WORDS.get(groq_status, "it couldn't be used")
    if _status_of(verdict) == _STATUS_OK:
        name, _ = _route_name(settings)
        _ai_back_on(state, route_pref=str(st.session_state.get(_ROUTE_PREF_KEY, "") or ""))
        st.session_state[_KEY_FLASH_KEY] = (
            "warning",
            f"That Groq key couldn't be used ({why}), so the interview keeps "
            f"using your {name or 'Setup'} API.",
        )
        return
    # Nothing works: keep the failed verdict so the box stays for another try.
    st.session_state[_API_CHECK_KEY] = groq_verdict or verdict
    if groq_status == _STATUS_INVALID_KEY:
        text = "Groq didn't accept that key. Check you copied the whole key and try again."
        kind = "error"
    elif groq_status == _STATUS_QUOTA:
        text = (
            "That key works, but its free Groq quota is used up for today. Try "
            "another key, or carry on without AI help for now."
        )
        kind = "warning"
    else:
        text = (
            "Couldn't reach Groq just now, so the key isn't confirmed yet. Try "
            "again in a moment — the interview carries on meanwhile."
        )
        kind = "warning"
    st.session_state[_KEY_FLASH_KEY] = (kind, text)


def _ai_back_on(state: Any, *, route_pref: str) -> None:
    """Switch the AI turns back on after a working API was found."""
    st.session_state[_AI_CHOICE_KEY] = True
    st.session_state[_AI_FORCE_ON_KEY] = True
    if state is not None:
        state.ai_mode = "on"
        state.ai_off_reason = ""
        state.ai_off_status = ""
        state.soft_failures = 0
        state.route_pref = route_pref
        # The explanation for the AI being off no longer applies.
        last = dict(st.session_state.get(_LAST_TURN_KEY) or {})
        last["ack"] = ""
        last["note"] = ""
        st.session_state[_LAST_TURN_KEY] = last


def _show_key_flash() -> None:
    flash = st.session_state.pop(_KEY_FLASH_KEY, None)
    if isinstance(flash, tuple) and len(flash) == 2:
        kind, text = flash
        {"success": st.success, "error": st.error}.get(kind, st.warning)(text)


def _key_form(settings: Any, state: Any, *, where: str) -> None:
    """A box and a button that take a Groq key and turn the AI on.

    Drawn wherever the interview can end up without its AI: the intro card
    and the live question. A form, so the key is sent with one click on the
    button or one press of Enter, and the box empties once it is used.
    """
    _show_key_flash()
    if not _needs_key_form(settings, state):
        return
    if _key_is_main_key(settings):
        # The box would write over the main key, so the key is changed where
        # it lives instead.
        st.caption(
            "The interview uses your Groq key from Setup. To use a different "
            "key, change it on Setup."
        )
        return
    try:
        from app.services import key_store

        remembered = bool(key_store.is_configured())
    except Exception:  # noqa: BLE001
        remembered = False

    with st.form(key=f"iv_groq_form_{where}", clear_on_submit=True, border=False):
        st.markdown("**Turn on AI help with a free Groq key**")
        col_key, col_btn = st.columns([3, 1], vertical_alignment="bottom")
        typed = col_key.text_input(
            "Groq API key",
            type="password",
            placeholder="gsk_…  paste your free Groq key here",
            key=f"iv_groq_key_{where}",
            label_visibility="collapsed",
        )
        submitted = col_btn.form_submit_button(
            "Turn on AI", type="primary", use_container_width=True
        )
        st.caption(
            "Get one free at console.groq.com/keys. It's used only for this "
            "interview"
            + (
                " and is remembered, encrypted, on this device."
                if remembered
                else " and kept for this session."
            )
        )
    # Streamlit's "Press Enter to submit form" hint overlaps the masked key
    # and the show/hide button at phone width; the button says the same.
    theme.html(
        f"<style>.st-key-iv_groq_form_{where} "
        '[data-testid="InputInstructions"]{display:none}</style>'
    )
    if submitted:
        _save_interview_key(typed, state)
        st.rerun()


def _new_state(ai_mode: str) -> Any:
    """A fresh interview state, set to the AI mode the user chose."""
    state = interview.InterviewState()  # type: ignore[union-attr]
    state.ai_mode = ai_mode
    return state


def _reset_turn_display(ack: str = "") -> None:
    st.session_state[_LAST_TURN_KEY] = {
        "kind": "next",
        "message": "",
        "ack": ack,
        "note": "",
    }


def _resume_turn_display(state: Any, ack: str = "") -> None:
    """The turn display for an interview picked up again from the intro card.

    A follow-up asked before the user left is still waiting for its reply:
    the service takes the next answer as that reply, unchecked, and adds it
    to the answer before it. So the follow-up is shown again — drawn as the
    bare question, it would be answered a second time and never get its
    reply. A follow-up that can no longer be found is dropped instead, and
    the question opens with its stored answer in the box to be replaced.
    """
    _reset_turn_display(ack)
    if not bool(getattr(state, "pending_follow", False)):
        return
    # The service's own lookup: the very follow-up the reply is sent with.
    finder = getattr(interview, "_last_follow_up", None)
    try:
        follow_up = str(finder(state) or "") if callable(finder) else ""
    except Exception:  # noqa: BLE001 - an odd transcript asks the question again
        follow_up = ""
    if follow_up:
        st.session_state[_LAST_TURN_KEY].update(kind="follow_up", message=follow_up)
        return
    state.pending_follow = False
    index = int(getattr(state, "index", 0) or 0)
    if str((getattr(state, "answers", {}) or {}).get(index, "") or "").strip():
        state.editing = index


def _start(ai_mode: str, *, ack: str = "") -> None:
    """Begin (or restart) the interview. Caller reruns.

    ``ack`` is shown above the first question: it is how a user who asked for
    the AI and could not have it finds that out, rather than wondering why no
    follow-up ever comes.
    """
    st.session_state[_STATE_KEY] = _new_state(ai_mode)
    st.session_state[_STARTED_KEY] = True
    st.session_state[_RESTART_CONFIRM_KEY] = False
    st.session_state[_SEQ_KEY] = int(st.session_state.get(_SEQ_KEY, 0)) + 1
    _reset_turn_display(ack)


def _questions() -> list:
    return list(getattr(interview, "QUESTIONS", None) or [])


def _current_question(state: Any) -> tuple[Any, int]:
    """The question the interview is on, plus its position in the bank."""
    questions = _questions()
    index = int(getattr(state, "index", 0) or 0)
    if index < 0 or index >= len(questions):
        return None, index
    return questions[index], index


def _answer_count(state: Any) -> int:
    """How many questions count as answered.

    Delegated to the service so the Finish gate, the caption and the
    profile build agree. A declined question ("none", "skip", "n/a") is
    stored but is not an answer, and three declines must not unlock a
    build that comes out empty.
    """
    try:
        return int(interview.progress(state)["answered"])  # type: ignore[union-attr]
    except Exception:  # noqa: BLE001 - an odd state must not break the header
        return 0


def _is_done(state: Any) -> bool:
    if bool(getattr(state, "done", False)):
        return True
    questions = _questions()
    return bool(questions) and int(getattr(state, "index", 0) or 0) >= len(questions)


# ---------------------------------------------------------------------------
# Turns
# ---------------------------------------------------------------------------


def _payload(result: Any) -> dict:
    """One turn's result, read defensively into the display dict."""
    return {
        "kind": str(getattr(result, "kind", "next") or "next"),
        "message": str(getattr(result, "message", "") or ""),
        "ack": str(getattr(result, "ack", "") or ""),
        "note": str(getattr(result, "note", "") or ""),
    }


def _land(payload: dict) -> None:
    """Show one turn's result and rerun.

    The rerun is what makes a single click land: the top bar, the rail and
    the profile panel are all drawn before this screen runs, so they only
    show the new turn on the next pass.
    """
    st.session_state[_LAST_TURN_KEY] = payload
    # The counter is what re-mounts the answer box empty, so it only moves
    # when the turn actually consumed the answer. A retry is the service
    # handing the same answer back to be improved: wiping it there would
    # delete the user's words at the exact moment they are asked to edit
    # them.
    if payload["kind"] != "retry":
        st.session_state[_SEQ_KEY] = int(st.session_state.get(_SEQ_KEY, 0)) + 1
    st.rerun()


_OFF_STATUS_VERDICTS = {
    "invalid_key": _STATUS_INVALID_KEY,
    "quota": _STATUS_QUOTA,
    "no_api": _STATUS_NO_KEY,
    "model_missing": "MODEL NOT ACCEPTED",
    "access_denied": "API ACCESS DENIED",
    "unsupported_provider": _STATUS_NO_MODEL,
}


def _after_ai_lost(state: Any, settings: Any) -> None:
    """A turn found the provider gone: say why, and try the fallback route.

    The cached verdict said "API OK", which would hide both the reason and
    the key box, so it is replaced with what the turn actually saw. When a
    Groq key was what failed and the Setup API works, the AI comes straight
    back on through the Setup API.
    """
    off_reason = str(getattr(state, "ai_off_reason", "") or "")
    if getattr(state, "ai_mode", "on") != "off" or off_reason != getattr(
        interview, "AI_OFF_PROVIDER", "provider_unavailable"
    ):
        return
    status = _OFF_STATUS_VERDICTS.get(
        str(getattr(state, "ai_off_status", "") or ""), _STATUS_CONNECTION
    )
    st.session_state[_API_CHECK_KEY] = SimpleNamespace(status=status)
    if not getattr(state, "route_pref", ""):
        default, main = _routes(settings)
        if default and main and default[0] == "groq" and main[0] != "groq":
            verdict = _probe(settings)
            if _status_of(verdict) == _STATUS_OK:
                st.session_state[_API_CHECK_KEY] = verdict
                _ai_back_on(state, route_pref=str(st.session_state.get(_ROUTE_PREF_KEY, "") or ""))


def _submit(state: Any, text: str, *, from_chip: bool) -> None:
    """Send one answer to the interview service, then rerun.

    The turn runs on a copy of the state, which takes the session's place
    only once the turn is complete. A second click on Send while the model
    is still reading starts a new run at once, and Streamlit stops this one
    at its next touch of the session, part-way through the turn. Changed in
    place, the state the new run reads would already hold this run's half
    of the turn: the answer would be taken twice, and a follow-up it replies
    to forgotten. On a copy, a stopped run — or a failed turn — leaves the
    state exactly as it found it, and the swap is itself a session write,
    which is where a stopped run is cut off.
    """
    settings = get_settings()
    turn = copy.deepcopy(state)
    turn.route_pref = str(st.session_state.get(_ROUTE_PREF_KEY, "") or "")
    try:
        with st.spinner("Reading your answer…"):
            result = interview.submit_answer(  # type: ignore[union-attr]
                turn, text, settings=settings, from_chip=from_chip
            )
    except Exception:  # noqa: BLE001 - a failed turn must not crash the screen
        _logger.error("Interview turn failed: %s", traceback.format_exc())
        payload = {
            "kind": "retry",
            "message": "Something went wrong with that answer. Send it again.",
            "ack": "",
            "note": "",
        }
    else:
        payload = _payload(result)
        _after_ai_lost(turn, settings)
        # A fallback may have switched the AI back on after the service wrote
        # its "working without AI" note; the note would now be wrong.
        if getattr(turn, "ai_mode", "off") == "on":
            payload["note"] = ""
        st.session_state[_STATE_KEY] = turn
    _land(payload)


def _skip(state: Any) -> None:
    """Move past the current question without answering it, then rerun.

    The move belongs to the service: :func:`interview.skip_question` files
    nothing under the question's key, validates nothing and follows nothing
    up, and records the skip in the transcript so the conversation still
    reads straight. Its result then goes through the same display path a
    sent answer takes, so a skip that lands on the last question ends the
    interview exactly the way a final answer does.
    """
    try:
        result = interview.skip_question(state)  # type: ignore[union-attr]
    except Exception:  # noqa: BLE001 - a failed skip must not crash the screen
        _logger.error("Interview skip failed: %s", traceback.format_exc())
        payload = {
            "kind": "retry",
            "message": "Something went wrong skipping that one. Try again.",
            "ack": "",
            "note": "",
        }
    else:
        payload = _payload(result)
        payload["ack"] = _SKIP_ACK
    _land(payload)


def _previous(state: Any) -> None:
    """Step back to the question before this one, then rerun.

    Any pending follow-up is dropped because it belonged to the question
    being left. The earlier answer stays in state and comes back in the box
    to be edited; sending replaces it, and Skip keeps it as it was.
    """
    index = int(getattr(state, "index", 0) or 0)
    if index <= 0:
        return
    back = getattr(interview, "previous_question", None)
    if callable(back):
        back(state)
    else:  # an older service: move the cursor only
        state.pending_follow = False
        state.done = False
        state.index = min(index, len(_questions())) - 1
    st.session_state[_SEQ_KEY] = int(st.session_state.get(_SEQ_KEY, 0)) + 1
    _reset_turn_display(_BACK_ACK)
    st.rerun()


# ---------------------------------------------------------------------------
# Completion
# ---------------------------------------------------------------------------


def _strength(state: Any) -> dict:
    try:
        return dict(interview.profile_strength(state) or {})  # type: ignore[union-attr]
    except Exception:  # noqa: BLE001 - the panel degrades to zero, never errors
        return {}


def _strength_tone(score: int) -> str:
    """The strength label's tone — same bands as the dossier screen's."""
    if score >= 80:
        return "ok"
    if score >= 60:
        return "t2"
    if score >= 40:
        return "warn"
    return "stop"


def _strength_band(score: int) -> str:
    if score >= 70:
        return "ok"
    if score >= 40:
        return "warn"
    return "stop"


def _record_strength(state: Any) -> None:
    """Publish the interview's own strength score, under its own key.

    ``dossier_validation`` is a reading of a folder of files: its score,
    its breakdown and its file list describe that folder and nothing else.
    Raising its score from here would leave an object claiming a strength
    those files never earned, with a breakdown that no longer adds up to
    it, so the folder's result is left exactly as the folder left it.
    """
    score = int(_strength(state).get("score", 0) or 0)
    st.session_state[_STRENGTH_KEY] = max(0, min(100, score))


def _is_interview_chunk(chunk: Any) -> bool:
    """True when this chunk is one the interview itself wrote."""
    name = str(
        getattr(interview, "PROFILE_FILE_NAME", "interview_profile.json")
    ).strip().lower()
    for attr in ("file_name", "file_path"):
        value = (
            chunk.get(attr) if isinstance(chunk, dict) else getattr(chunk, attr, "")
        )
        if str(value or "").strip().lower() == name:
            return True
    return False


def _interview_meta(state: Any) -> dict:
    """The interview's own keys on ``evidence_index_meta``.

    ``interview.build_evidence`` writes these on the pure-interview path.
    The gap-fill path re-indexes the folder's chunks and the interview chunk
    together through the folder's own builder, which knows nothing about an
    interview, so the same keys are merged in by hand there — otherwise the
    two paths hand downstream screens meta of two different shapes.
    """
    return {
        "source": "interview",
        "error_message": (
            "Profile built from your files plus the guided interview; "
            "evidence extracted with the local JSON scanner."
        ),
        "interview_strength": int(_strength(state).get("score", 0) or 0),
        "interview_answers": _answer_count(state),
        # Only this path carries the folder's files. Analysis reads it to
        # decide whether the folder's own score still speaks for the profile.
        "with_folder": True,
    }


def _joins_folder() -> bool:
    """True when the interview is added to a folder's files, not put in their place.

    "Interview me instead" replaces a folder read earlier; only the
    thin-folder offer adds the interview to the folder. Sessions from before
    the entry was recorded keep the old behaviour.
    """
    ss = st.session_state
    entry = str(ss.get(_ENTRY_KEY, "") or "")
    # The profile in use has the last word over the button, though. Once a
    # gap-filling interview is built into the folder, Dossier stops offering
    # the gap fill, so "Interview me instead" is the only way back to carry
    # on with it — and carrying on is not asking to throw the folder away.
    meta_now = ss.get("evidence_index_meta")
    merged = (
        ss.get(_SOURCE_KEY) == "interview"
        and isinstance(meta_now, dict)
        and bool(meta_now.get("with_folder"))
    )
    return entry != "chooser" or merged


def adds_to_folder() -> bool:
    """True when the profile in use is this interview, kept with the folder's files.

    The dossier screen asks before it reads the folder again. That read
    builds the profile from the files alone, so unless the interview is
    added back (:func:`rebuild_profile`), a gap-filling interview's answers
    drop out of the profile — and out of every proposal — without a word.
    """
    ss = st.session_state
    return (
        ss.get(_SOURCE_KEY) == "interview"
        and ss.get(_STATE_KEY) is not None
        and _joins_folder()
    )


def rebuild_profile(folder_chunks: Any = None, *, state: Any = None) -> bool:
    """Build the profile from the interview's answers, on top of a folder's chunks.

    With ``folder_chunks``, the interview chunk is added to them and the
    whole set is re-indexed, so a gap-filling interview strengthens the
    folder rather than replacing it; without, the profile is the answers
    alone. Either way it writes exactly the session state a dossier read
    writes, plus ``profile_source`` and the interview's strength, and drops
    what was built on the previous profile.

    :func:`_finish` builds through here, and so does the dossier screen when
    it reads a gap-filled folder again or loses its files, so the two
    routes can never build the same profile two different ways. Returns
    False, with the session untouched, when no profile comes out of it.
    """
    ss = st.session_state
    if state is None:
        state = ss.get(_STATE_KEY)
    if interview is None or state is None:
        return False
    # Only the folder's own chunks are something to gap-fill. A chunk this
    # interview wrote on an earlier pass is dropped rather than built on:
    # keeping it would append a second copy of the same chunk_id every time
    # the profile is built and double the proof points. Dropping it is also
    # what makes the rebuild idempotent — building twice gives one index.
    base_chunks = [
        chunk for chunk in (folder_chunks or []) if not _is_interview_chunk(chunk)
    ]
    try:
        chunks = list(interview.to_chunks(state))  # type: ignore[union-attr]
        if base_chunks:
            chunks = base_chunks + chunks
            proofs, profile, meta = build_evidence_index(chunks)
            meta = dict(meta or {})
            meta.update(_interview_meta(state))
        else:
            proofs, profile, meta = (
                interview.build_evidence(state)  # type: ignore[union-attr]
            )
    except Exception:  # noqa: BLE001 - the caller decides what to say
        return False
    if not proofs:
        return False

    ss["dossier_chunks"] = chunks
    ss["dossier_read"] = True
    ss["dossier_read_error"] = False
    ss["evidence_index"] = proofs
    ss["canonical_profile"] = profile
    ss["evidence_index_meta"] = meta
    ss[_SOURCE_KEY] = "interview"
    # The job fields were read off a screenshot against the previous profile,
    # and ``dossier_screen._reset_downstream`` drops them whenever the folder
    # route rebuilds. This route rebuilds the same evidence, so it drops the
    # same key: a profile built either way must leave the same state behind.
    ss["extracted_job_fields"] = None
    _record_strength(state)
    # New evidence means the verdict and the proposal built on the old
    # evidence are stale, and a stale proposal left on screen reads as the
    # current one. ``dossier_screen._reset_downstream`` clears them for
    # exactly this reason whenever the folder route rebuilds; the interview
    # route rebuilds the same keys, so it clears them too.
    clear_opportunity_state(ss)
    return True


def _finish(state: Any) -> None:
    """Build the evidence index from the interview and go to Job Screenshot.

    When a dossier was already read, the interview chunk is added to it and
    the whole set is re-indexed, so a gap-filling interview strengthens the
    folder rather than replacing it (see :func:`rebuild_profile`).
    """
    ss = st.session_state
    # Only the folder's own chunks are something to gap-fill: a chunk this
    # interview wrote on an earlier pass is not a folder.
    base_chunks = [
        chunk
        for chunk in (ss.get("dossier_chunks") or [])
        if not _is_interview_chunk(chunk)
    ]
    gap_fill = bool(base_chunks and ss.get("dossier_read")) and _joins_folder()

    with st.spinner("Building your profile…"):
        built = rebuild_profile(base_chunks if gap_fill else None, state=state)

    if not built:
        # An empty index would leave the next step locked, so stop here with a
        # message instead of advancing into a dead end.
        st.error(_BUILD_FAILED_MESSAGE)
        return

    ss["current_step"] = "screenshot"
    st.rerun()


# ---------------------------------------------------------------------------
# Read-only views
# ---------------------------------------------------------------------------


def _stringify(value: Any, *, limit: int = 120) -> str:
    """One short line for a profile value of any shape."""
    if value is None:
        return ""
    if isinstance(value, (list, tuple, set)):
        text = ", ".join(str(v).strip() for v in value if str(v).strip())
    elif isinstance(value, dict):
        text = ", ".join(f"{k}: {v}" for k, v in value.items() if v)
    else:
        text = str(value).strip()
    text = " ".join(text.split())
    if len(text) > limit:
        text = text[: limit - 1].rstrip() + "…"
    return text


def _profile_pairs(state: Any, *, limit: int = 12) -> list[tuple[str, str]]:
    try:
        profile = interview.build_profile_dict(state) or {}  # type: ignore[union-attr]
    except Exception:  # noqa: BLE001 - the panel is a preview, never a blocker
        return []
    pairs: list[tuple[str, str]] = []
    for key, value in profile.items():
        text = _stringify(value)
        if not text:
            continue
        pairs.append((str(key).replace("_", " ").capitalize(), text))
        if len(pairs) >= limit:
            break
    return pairs


# The transcript is written by the service; read it defensively so a change
# of wording in its entries can never break the screen.
_ROLE_KEYS = ("role", "speaker", "who", "from")
_TEXT_KEYS = ("text", "content", "message", "answer", "body")
_USER_ROLES = {"user", "you", "candidate", "freelancer", "human"}


def _transcript_items(state: Any) -> list[dict]:
    entries = list(getattr(state, "transcript", None) or [])
    items: list[dict] = []
    for entry in entries[-_TRANSCRIPT_TAIL:]:
        if not isinstance(entry, dict):
            continue
        role = ""
        for key in _ROLE_KEYS:
            if entry.get(key):
                role = str(entry[key])
                break
        text = ""
        for key in _TEXT_KEYS:
            if entry.get(key):
                text = str(entry[key])
                break
        if not text.strip():
            continue
        who = "You" if role.strip().lower() in _USER_ROLES else "Interviewer"
        items.append({"title": who, "body": text.strip()})
    return items


def _render_transcript(state: Any) -> None:
    """The conversation so far.

    Deliberately not inside a bordered panel: a keyed panel replays its
    entrance animation on every rerun, and this block redraws on every send.
    """
    items = _transcript_items(state)
    if not items:
        return
    theme.section_label("Conversation so far")
    theme.evidence_list(items)


# ---------------------------------------------------------------------------
# Start over
# ---------------------------------------------------------------------------
#
# One click used to be enough to delete a whole bank of answers — up to 63 of
# them, typed by hand, with nothing that could bring them back. So the first
# click only asks, and the second one, which says what it does, is the one
# that clears.


def _restart_click(target: Any, key: str, *, use_container_width: bool = False) -> str:
    """Draw "Start over" as a two-step confirmation.

    Returns the click this run produced — ``"ask"``, ``"confirm"``,
    ``"cancel"`` or ``""``. ``target`` is whatever the buttons should be drawn
    into (``st`` or a column). Nothing is decided here: the caller acts once
    its card is finished, the way every other click on this screen is handled.
    """
    if not st.session_state.get(_RESTART_CONFIRM_KEY):
        if target.button(
            "Start over",
            key=key,
            use_container_width=use_container_width,
            help="Clear every answer and begin again. You'll be asked to confirm.",
        ):
            return "ask"
        return ""
    clicked = ""
    if target.button(
        "Yes, delete my answers",
        key=f"{key}_confirm",
        use_container_width=use_container_width,
        help="This cannot be undone.",
    ):
        clicked = "confirm"
    if target.button(
        "Keep my answers",
        key=f"{key}_cancel",
        use_container_width=use_container_width,
        help="Leave the interview exactly as it is.",
    ):
        clicked = clicked or "cancel"
    return clicked


def _restart_warning(state: Any) -> None:
    """What the confirm click is about to cost, in answers."""
    answered = _answer_count(state)
    built = st.session_state.get(_SOURCE_KEY) == "interview"
    if answered:
        st.warning(
            f"Start over deletes {answered} answer"
            + ("" if answered == 1 else "s")
            + (" and the profile built from them," if built else "")
            + " and begins again from the first question. This can't be undone."
        )
    else:
        st.warning(
            "Start over begins again from the first question. This can't be "
            "undone."
        )


def _chosen_mode(settings: Any, ai_on: bool) -> tuple[str, str]:
    """The AI mode to start in, plus what to say when it can't be the one asked for.

    This is where the live probe happens: the user has chosen to start, so a
    network call is something they asked for rather than the price of opening
    the screen. :func:`_ai_ready` caches the verdict, so the reruns that carry
    the conversation never repeat it.
    """
    if not ai_on:
        return "off", ""
    # A failed check is asked again when the user starts or resumes: that is
    # their decision, and a dropped connection an hour ago should not keep
    # the AI off for the rest of the session.
    if _checked() and not _cached_ai_ready():
        st.session_state.pop(_API_CHECK_KEY, None)
    if _ai_ready(settings):
        return "on", str(st.session_state.get(_ROUTE_NOTE_KEY, "") or "")
    return "off", _ai_off_reason()


def _drop_interview_profile() -> None:
    """Take a deleted interview's answers out of the profile the app is using.

    A folder read before a gap-filling interview is rebuilt on its own;
    otherwise the profile is cleared, which locks Job Screenshot again until
    a new one is built.
    """
    ss = st.session_state
    if ss.get(_SOURCE_KEY) != "interview":
        return
    base = [c for c in (ss.get("dossier_chunks") or []) if not _is_interview_chunk(c)]
    if base:
        try:
            proofs, profile, meta = build_evidence_index(base)
        except Exception:  # noqa: BLE001 - fall through to a clean slate
            proofs, profile, meta = [], None, {}
        ss["dossier_chunks"] = base
        ss["evidence_index"] = proofs or None
        ss["canonical_profile"] = profile if proofs else None
        ss["evidence_index_meta"] = meta if proofs else None
        ss["dossier_read"] = bool(proofs)
        ss[_SOURCE_KEY] = "dossier"
    else:
        for key in ("dossier_chunks", "evidence_index", "canonical_profile", "evidence_index_meta"):
            ss[key] = None
        ss["dossier_read"] = False
        ss[_SOURCE_KEY] = None
    ss[_STRENGTH_KEY] = None
    ss["extracted_job_fields"] = None
    clear_opportunity_state(ss)


def _apply_restart(click: str, *, settings: Any, ai_on: bool) -> None:
    """Act on a "Start over" click, then rerun."""
    if click == "ask":
        st.session_state[_RESTART_CONFIRM_KEY] = True
    elif click == "cancel":
        st.session_state[_RESTART_CONFIRM_KEY] = False
    elif click == "confirm":
        _drop_interview_profile()
        mode, ack = _chosen_mode(settings, ai_on)
        _start(mode, ack=ack)  # clears the confirm step itself
    else:
        return
    st.rerun()


# ---------------------------------------------------------------------------
# Cards
# ---------------------------------------------------------------------------


def _ai_choice(state: Any, *, ai_ready: bool) -> bool:
    """The AI toggle's value: what the user last chose, not a fresh default.

    Read from a plain session key — and from the interview state behind it —
    because the toggle's own key is collected while the interview runs. An
    explicit "off" stays off across that gap, and an explicit "on" stays on.
    """
    if not ai_ready:
        return False
    stored = st.session_state.get(_AI_CHOICE_KEY)
    if isinstance(stored, bool):
        return stored
    if state is not None:
        return str(getattr(state, "ai_mode", "") or "").strip().lower() == "on"
    return True


def _card_intro(settings: Any) -> None:
    """What the interview is, and the one button that starts it."""
    state = st.session_state.get(_STATE_KEY)
    total = len(_questions())
    # Nobody has probed the provider yet unless an earlier start did: opening
    # this card is not a decision, so it must not spend a call finding out.
    # The AI is offered whenever there is a key to try it with — the probe
    # runs on the way in to the first question, and a failed one is asked
    # again on every Start or Resume (see :func:`_chosen_mode`), so a
    # provider that was down earlier in the session does not lock the toggle
    # off for good.
    checked = _checked()
    # With no key at all the answer is already known without a probe.
    has_key = _has_interview_key(settings)
    ai_ready = has_key

    with st.container(border=True, key="ups_panel_interview_1"):
        theme.section_label("Answer questions instead of uploading files")
        st.markdown(
            "The app asks about your work — what you do, who you do it for, "
            "and the results you have delivered. Your answers become the same "
            "profile evidence a folder of files would produce, and every "
            "proposal is grounded in them."
        )
        st.markdown(
            "**Your answers are saved exactly as you type them** — word for "
            "word, nothing rewritten. The AI reads them to check an answer "
            "fits the question, to ask a follow-up when something is "
            "missing, and to keep the conversation moving."
        )
        if total:
            st.caption(
                f"{total} questions, grouped into short sections. You can skip "
                "any question and finish whenever you like."
            )

        # Set through session state, before the widget exists this run, only
        # when a key was just accepted; otherwise seeded by ``value=`` when
        # the widget is new. Never both, which Streamlit warns about.
        toggle_seed: dict = {}
        if st.session_state.pop(_AI_FORCE_ON_KEY, False) and ai_ready:
            st.session_state[_AI_TOGGLE_KEY] = True
        elif _AI_TOGGLE_KEY not in st.session_state:
            toggle_seed["value"] = _ai_choice(state, ai_ready=ai_ready)
        ai_on = st.toggle(
            "Let the AI guide the interview",
            key=_AI_TOGGLE_KEY,
            disabled=not ai_ready,
            **toggle_seed,
            help=(
                "The AI checks each answer fits the question, asks the odd "
                "follow-up, and phrases the next question. Turn it off to be "
                "asked the questions as written. Your answers are stored as "
                "you typed them either way."
            ),
        )
        # Remembered outside the widget, because the widget's key does not
        # survive the reruns that draw the question card instead of this one.
        # A disabled toggle reads False whatever the user meant, so having no
        # key to try is not allowed to overwrite their choice.
        if ai_ready:
            st.session_state[_AI_CHOICE_KEY] = bool(ai_on)
        if checked and not _cached_ai_ready():
            st.caption(_ai_off_reason())
            if has_key:
                st.caption(
                    "It is checked again each time you start or resume with "
                    "the AI on."
                )
        elif not has_key:
            st.caption(
                "No API key is available for the interview, so the AI is off. "
                "Add a free Groq key below to turn it on — or start without "
                "it and add one any time during the interview. "
                + _ANSWERS_VERBATIM
            )
        else:
            name, is_setup = _route_name(settings)
            if name:
                st.caption(
                    f"The AI runs on your {name} API from Setup."
                    if is_setup
                    else f"The AI runs on your {name} key, so the interview "
                    "doesn't use your main API."
                )
            if not checked:
                st.caption(
                    "It is checked once, when you start. If it can't be "
                    "reached the interview carries on without it."
                )
        if st.session_state.get(_ROUTE_NOTE_KEY):
            st.caption(_plain(st.session_state[_ROUTE_NOTE_KEY]))

        _key_form(settings, state, where="intro")

        col_start, col_back = st.columns([2, 1])
        start_clicked = col_start.button(
            "Resume the interview" if state is not None else "Start the interview",
            type="primary",
            key="interview_start_btn",
            use_container_width=True,
        )
        back_clicked = col_back.button(
            "Back to Dossier",
            key="back_to_dossier_from_interview",
            use_container_width=True,
        )
        restart_click = ""
        if state is not None:
            if st.session_state.get(_RESTART_CONFIRM_KEY):
                _restart_warning(state)
            restart_click = _restart_click(st, "interview_restart_btn")

    if start_clicked:
        mode, ack = _chosen_mode(settings, bool(ai_on))
        if state is None:
            _start(mode, ack=ack)
        else:
            state.ai_mode = mode
            state.route_pref = str(st.session_state.get(_ROUTE_PREF_KEY, "") or "")
            if mode == "on":
                state.ai_off_reason = ""
                state.ai_off_status = ""
                state.soft_failures = 0
            st.session_state[_STARTED_KEY] = True
            st.session_state[_RESTART_CONFIRM_KEY] = False
            _resume_turn_display(state, ack)
        st.rerun()
    if restart_click:
        _apply_restart(restart_click, settings=settings, ai_on=bool(ai_on))
    if back_clicked:
        st.session_state.current_step = "dossier"
        st.rerun()


def _card_question(state: Any, question: Any, index: int, *, debug: bool) -> None:
    """The live question, its options, the answer box and the turn controls."""
    questions = _questions()
    total = len(questions)
    answered = _answer_count(state)
    last = st.session_state.get(_LAST_TURN_KEY) or {}
    kind = str(getattr(question, "kind", "text") or "text")
    options = [str(o) for o in (getattr(question, "options", None) or [])]
    awaiting_reply = str(last.get("kind", "")) in ("retry", "follow_up")

    picked: list[str] = []
    with st.container(border=True, key="ups_panel_interview_2"):
        theme.section_label(str(getattr(question, "section", "") or "Interview"))
        theme.html(theme.meter(100.0 * index / total if total else 0.0))
        st.caption(
            f"Question {min(index + 1, total)} of {total} · {answered} answered"
        )
        # Always on screen, so whether the AI is judging the answers — and
        # which one — is never a guess: the faint note that used to say so
        # was easy to miss.
        if str(getattr(state, "ai_mode", "") or "") == "on":
            name, _ = _route_name(get_settings())
            theme.html(
                theme.tag(f"AI check on · {name or 'AI'} reviews every answer", "ok")
            )
        else:
            theme.html(
                theme.tag("AI check off · basic checks only", "warn")
            )
        if st.session_state.get(_ROUTE_PREF_KEY) == "main" and st.session_state.get(_ROUTE_NOTE_KEY):
            st.caption(_plain(st.session_state[_ROUTE_NOTE_KEY]))

        if last.get("ack"):
            st.caption(_plain(last["ack"]))

        # The service's reply is model-written, so it goes through a plain
        # Streamlit element — never through a theme helper that takes markup —
        # and is escaped, so "$10 or $20" reads as money, not maths.
        if awaiting_reply and last.get("message"):
            st.info(_plain(last["message"]))
            st.caption(f"Original question: {_plain(getattr(question, 'text', ''))}")
        else:
            st.markdown(f"**{_plain(getattr(question, 'text', ''))}**")

        if last.get("note"):
            st.caption(_plain(last["note"]))

        # After Previous, the earlier answer comes back to be edited.
        editing = getattr(state, "editing", None) == index
        earlier = str((getattr(state, "answers", {}) or {}).get(index, "") or "") if editing else ""
        if editing and earlier and kind in ("chips", "multi"):
            st.caption(f"Your earlier answer: {_plain(earlier)}")
        if bool(getattr(question, "self_proof", False)):
            st.caption(
                "Be specific here — this answer becomes proof the proposals quote."
            )

        # The sequence counter is part of every answer widget's key, so the
        # box and the picked options re-mount empty once a turn has consumed
        # them — and keep what is in them through a re-ask, the one turn that
        # asks the user to improve what they just sent.
        seq = int(st.session_state.get(_SEQ_KEY, 0))

        # Option buttons send straight away: one click, one turn. They stay on
        # screen through a re-ask, because a re-ask on an options question is
        # the service asking the user to pick one of them.
        if options and kind in ("chips", "multi"):
            if kind == "chips":
                cols = st.columns(min(3, len(options)))
                for position, option in enumerate(options):
                    if cols[position % len(cols)].button(
                        option,
                        key=f"iv_chip_{index}_{position}",
                        use_container_width=True,
                    ):
                        _submit(state, option, from_chip=True)
            else:
                # Typing a name that is not in the list adds it as a new
                # option, so a sector the list misses can be picked here too.
                picked = st.multiselect(
                    "Pick everything that applies",
                    options,
                    key=f"iv_multi_{index}_{seq}",
                    accept_new_options=True,
                    placeholder="Pick from the list, or type your own and press Enter",
                )

        # On a pick-several question the box is the "not in the list" half of
        # the answer, so it carries a visible label saying so; elsewhere it is
        # the answer itself and the question above is its label.
        multi_box = bool(options) and kind == "multi"
        # An answer and its follow-up replies are stored joined, so the one
        # coming back to be edited can run past the limit for one answer.
        # The box holds all of it: Streamlit cuts a box's value to
        # ``max_chars`` out of sight, and Send would then store what was left.
        box_limit = _MAX_ANSWER_CHARS
        if editing and kind == "text":
            box_limit = max(box_limit, len(earlier))
        text = st.text_area(
            "Not in the list? Type it here" if multi_box else "Your answer",
            key=f"iv_answer_{index}_{seq}",
            value=earlier if (editing and kind == "text") else "",
            placeholder=str(
                getattr(question, "placeholder", "") or "Type your answer…"
            ),
            height=110,
            max_chars=box_limit,
            label_visibility="visible" if multi_box else "collapsed",
        )
        if box_limit > _MAX_ANSWER_CHARS:
            st.caption(
                f"Your earlier answer, with what you added after a follow-up, is "
                f"longer than the {_MAX_ANSWER_CHARS:,} characters one answer "
                f"can hold. Skip "
                f"keeps it as it is; to change it, shorten it to "
                f"{_MAX_ANSWER_CHARS:,} characters first."
            )

        col_send, col_prev, col_skip, col_finish = st.columns([2, 1, 1, 1])
        send_clicked = col_send.button(
            "Send",
            type="primary",
            key="iv_send_btn",
            use_container_width=True,
        )
        can_go_back = index > 0
        prev_clicked = col_prev.button(
            "Previous",
            key="iv_prev_btn",
            use_container_width=True,
            disabled=not can_go_back,
            help=(
                "Go back to the question before this one to change your "
                "answer. Sending replaces it; Skip keeps it."
                if can_go_back
                else "This is the first question."
            ),
        )
        skip_clicked = col_skip.button(
            "Skip",
            key="iv_skip_btn",
            use_container_width=True,
            help="Move on without answering this one.",
        )
        can_finish = answered >= _MIN_ANSWERS_TO_FINISH
        finish_clicked = col_finish.button(
            "Finish",
            key="iv_finish_early_btn",
            use_container_width=True,
            disabled=not can_finish,
            help=(
                "Build my profile from what I have answered so far."
                if can_finish
                else f"Answer at least {_MIN_ANSWERS_TO_FINISH} questions first."
            ),
        )

        if debug:
            st.caption(
                f"use: {getattr(question, 'use', '—')} · kind: {kind} · "
                f"AI turns used: {getattr(state, 'calls_used', 0)} of "
                f"{getattr(interview, 'MAX_CALLS_PER_INTERVIEW', '—')} · "
                f"mode: {getattr(state, 'ai_mode', '—')}"
            )

        # Below the controls, so the answer box stays where the eye expects
        # it; shown only while the AI is off for want of a working key.
        if str(getattr(state, "ai_mode", "") or "") != "on":
            st.divider()
            _key_form(get_settings(), state, where="question")
        else:
            _show_key_flash()

        # Clicks are read first and acted on afterwards, so every widget in
        # this card has already handed over its value.
        if send_clicked:
            typed = (text or "").strip()
            # A "multi" question asks the user to pick all that apply *or*
            # add their own, so the ticks and the typed words are two halves
            # of one answer. Sending either half on its own would silently
            # throw the other away.
            answer = ", ".join([*picked, typed]) if typed else ", ".join(picked)
            # An answer made only of option picks is the same thing a chip
            # button sends: a choice from a fixed list the model never has
            # to read. Sent as a chip it costs no call against the free tier.
            # Typed words are not on that list, so as soon as there are any
            # the whole answer goes through validation.
            # A name typed into the dropdown is a new option, not one of the
            # list's, so it goes through validation like typed words do.
            new_picks = [p for p in picked if p not in options]
            from_picks = bool(picked) and not typed and not new_picks
            if not answer:
                st.warning("Type an answer first, or use Skip.")
            elif len(typed) > _MAX_ANSWER_CHARS:
                # Only the long earlier answer above gets this far, and the
                # service keeps the first ``_MAX_ANSWER_CHARS`` of an answer:
                # sent, it would lose its end without a word.
                st.warning(
                    f"That answer is longer than the {_MAX_ANSWER_CHARS:,} "
                    "characters one answer can hold, so sending it would cut "
                    "off the end. Shorten it first, or use Skip to keep your "
                    "earlier answer as it is."
                )
            else:
                _submit(state, answer, from_chip=from_picks)

    if prev_clicked:
        _previous(state)
    if skip_clicked:
        _skip(state)
    if finish_clicked:
        # An answer typed or ticked but not sent would be lost without a word.
        # After Previous the box holds the stored answer; that one is saved.
        unsent = (text or "").strip()
        if editing and unsent == earlier.strip():
            unsent = ""
        if unsent or picked:
            st.warning(
                "You have an answer here that isn't sent yet. Send it (or clear "
                "the box) first, then Finish."
            )
        else:
            _finish(state)


def _card_profile(state: Any, *, debug: bool) -> None:
    """The profile as it stands, so the user sees the interview paying off."""
    with st.container(border=True, key="ups_panel_interview_3"):
        theme.section_label("Your profile so far")
        strength = _strength(state)
        score = int(strength.get("score", 0) or 0)
        label = str(strength.get("label", "") or "")
        theme.kpis(
            [
                {
                    "lab": "Profile strength",
                    "val": f"{score}/100",
                    "icon": "spark",
                    "delta": label,
                    "delta_kind": _strength_tone(score),
                }
            ],
            columns=1,
        )
        theme.html(theme.meter(score, _strength_band(score)))

        pairs = _profile_pairs(state)
        if pairs:
            theme.kv_grid(pairs, columns=2)
        else:
            st.caption("Answer a few questions and your profile fills in here.")

        if debug:
            breakdown = strength.get("breakdown") or {}
            if isinstance(breakdown, dict) and breakdown:
                for key, value in breakdown.items():
                    st.write(f"- {key}: **{value}**")


def _card_finish(state: Any, settings: Any) -> None:
    """The end of the bank: build the profile and move on.

    Build is gated by the same minimum the in-question Finish button uses.
    Reaching the end of the bank is not the same as having answered it: a
    user who skipped every question arrives here with nothing to build
    from, and an ungated button would only hand them an error. So the
    button waits, and the card says what to do instead — including the way
    back to the folder route, which is the only other way out of here.
    """
    answered = _answer_count(state)
    can_build = answered >= _MIN_ANSWERS_TO_FINISH
    with st.container(border=True, key="ups_panel_interview_4"):
        theme.section_label("Interview complete")
        if can_build:
            st.success(f"That's everything — {answered} answers recorded.")
            st.write(
                "Next the app turns your answers into proof points, the same "
                "way it does with a folder of files."
            )
        else:
            st.warning(
                (
                    "That's the end of the questions, but none of them were "
                    "answered"
                    if answered == 0
                    else f"That's the end of the questions, but only "
                    f"{answered} were answered"
                )
                + f" — fewer than the {_MIN_ANSWERS_TO_FINISH} a profile "
                "needs. Go back to the questions and answer a few, or build "
                "your profile from a folder of files instead."
            )
        if st.session_state.get(_RESTART_CONFIRM_KEY):
            _restart_warning(state)
        col_build, col_questions, col_restart, col_back = st.columns([2, 1, 1, 1])
        questions_clicked = col_questions.button(
            "Back to the questions",
            key="iv_back_to_questions_btn",
            use_container_width=True,
            help="Return to the last question. Use Previous to reach any you skipped.",
        )
        build_clicked = col_build.button(
            "Build my profile and continue",
            type="primary",
            key="iv_finish_btn",
            use_container_width=True,
            disabled=not can_build,
            help=(
                "Build my profile from what I have answered so far."
                if can_build
                else f"Answer at least {_MIN_ANSWERS_TO_FINISH} questions first."
            ),
        )
        restart_click = _restart_click(
            col_restart, "iv_restart_from_done_btn", use_container_width=True
        )
        back_clicked = col_back.button(
            "Back to Dossier",
            key="back_to_dossier_from_done_interview",
            use_container_width=True,
            help="Build your profile from a folder of files instead.",
        )

    if build_clicked:
        _finish(state)
    if questions_clicked:
        _previous(state)
    if restart_click:
        # The user's own choice, not the state's mode: an interview whose AI
        # dropped out mid-way should get a fresh check, not stay off.
        choice = st.session_state.get(_AI_CHOICE_KEY)
        _apply_restart(
            restart_click,
            settings=settings,
            ai_on=choice if isinstance(choice, bool) else True,
        )
    if back_clicked:
        st.session_state.current_step = "dossier"
        st.rerun()


# ---------------------------------------------------------------------------
# Public render
# ---------------------------------------------------------------------------


def render() -> None:
    if not st.session_state.get("api_ok"):
        st.error("This step is locked. Run the API check on the Setup screen first.")
        if st.button("Back to Setup", key="back_to_setup_from_interview"):
            st.session_state.current_step = "setup"
            st.rerun()
        return

    settings = get_settings()
    debug = bool(getattr(settings, "show_debug_panel", False))

    theme.screen_head(
        "dossier",
        "Let's build your profile",
        "No folder of files? Answer questions instead — the app builds the "
        "same evidence from <b>your own words</b> and grounds every proposal "
        "in it.",
    )

    if not is_available() or not _questions():
        st.error(
            "The interview isn't available right now. You can still build "
            "your profile from a folder of files."
        )
        if st.button("Back to Dossier", key="back_to_dossier_unavailable"):
            st.session_state.current_step = "dossier"
            st.rerun()
        return

    # No provider probe here. Arriving on this screen is not a decision, and
    # a live call fired before the user has chosen anything spends their free
    # quota on a screen they may be about to leave. The one check runs when
    # they press Start (see :func:`_chosen_mode`) and is cached for the rest
    # of the session, so the reruns that carry the conversation never repeat
    # it. Its verdict decides whether the AI turns run and what the user is
    # told; it never stops the interview.

    state = st.session_state.get(_STATE_KEY)
    if state is None or not st.session_state.get(_STARTED_KEY):
        _card_intro(settings)
        return

    if _is_done(state):
        _card_finish(state, settings)
        _card_profile(state, debug=debug)
        _render_transcript(state)
        return

    question, index = _current_question(state)
    if question is None:
        # Defensive: an index past the bank means the interview is over.
        state.done = True
        _card_finish(state, settings)
        return

    col_chat, col_profile = st.columns([3, 2])
    with col_chat:
        _card_question(state, question, index, debug=debug)
    with col_profile:
        _card_profile(state, debug=debug)

    with col_chat:
        _render_transcript(state)

    if st.button("Back to Dossier", key="back_to_dossier_from_running_interview"):
        st.session_state.current_step = "dossier"
        st.rerun()