File size: 43,334 Bytes
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357ee36
6303ae6
357ee36
6303ae6
357ee36
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93411b2
8edf4e8
 
6303ae6
 
 
93411b2
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93411b2
 
 
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
c9d9189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
c9d9189
6303ae6
c9d9189
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
c9d9189
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357ee36
 
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
f9a06ca
 
 
 
357ee36
 
 
 
f9a06ca
 
6303ae6
f9a06ca
 
357ee36
 
 
 
 
f9a06ca
 
 
357ee36
f9a06ca
357ee36
 
 
f9a06ca
6303ae6
357ee36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
 
 
357ee36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9a06ca
357ee36
f9a06ca
357ee36
 
 
 
 
f9a06ca
 
 
 
 
 
 
 
 
 
 
 
 
 
8edf4e8
 
 
 
f9a06ca
 
8edf4e8
 
 
 
 
f9a06ca
 
 
357ee36
 
 
 
 
 
 
 
 
 
 
 
 
 
f9a06ca
 
 
357ee36
 
 
 
 
 
 
 
 
 
f9a06ca
 
 
 
 
 
 
357ee36
f9a06ca
 
6303ae6
 
 
 
 
 
 
 
c9d9189
6303ae6
 
 
f9a06ca
 
 
 
357ee36
 
 
 
 
 
 
 
 
 
 
 
f9a06ca
 
 
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
 
 
 
 
357ee36
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357ee36
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
c9d9189
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93411b2
 
6303ae6
 
 
93411b2
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
357ee36
c9d9189
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
357ee36
 
 
 
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8edf4e8
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8edf4e8
 
 
 
 
 
 
 
 
 
 
 
357ee36
6303ae6
 
 
 
 
 
 
 
 
 
 
 
357ee36
 
 
 
 
 
 
 
6303ae6
 
357ee36
 
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8edf4e8
357ee36
 
 
 
 
 
 
6303ae6
 
 
 
93411b2
 
357ee36
 
93411b2
 
 
357ee36
93411b2
357ee36
93411b2
6303ae6
 
 
357ee36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9d9189
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93411b2
 
 
 
 
 
 
 
 
357ee36
 
93411b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8edf4e8
93411b2
8edf4e8
 
 
 
93411b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8edf4e8
 
 
 
 
 
 
93411b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357ee36
 
6303ae6
 
357ee36
 
 
6303ae6
 
 
93411b2
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
 
 
 
 
357ee36
6303ae6
 
 
 
 
 
 
 
 
 
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
"""Screen 2: Dossier folder and profile evidence.

Normal (non-technical) flow — a single button:

* **Continue to Job Screenshot** — the user points the tool at a local
  folder and clicks once. That one button runs the full backend chain
  silently behind a spinner — ``validate`` → ``read_dossier`` →
  ``create_evidence_index`` — then advances. The user never sees the
  intermediate "Validate Folder" / "Read Dossier" / "Create Evidence Index"
  steps, the file count, or the dossier-strength score. A folder that can't
  be validated/read shows one clean inline error and keeps the user on the
  page — never a traceback.

Original files never leave the user's machine. The file count, the
dossier-strength score, the separate Validate/Read/Index buttons, the
chunk/proof-point stats, per-file source types, and the scoring rubric
appear only when ``SHOW_DEBUG_PANEL=true``.
"""

from __future__ import annotations

import hashlib
import os
import shutil
import tempfile
from contextlib import contextmanager
from pathlib import Path

import streamlit as st

from app.config import clear_opportunity_state, get_settings, save_dossier_path
from app.models.schemas import SOURCE_TYPE_LABELS
from app.services.dossier_reader import (
    DossierReadSummary,
    read_dossier,
    summarize_chunks,
)
from app.services.evidence_index import build_evidence_index
from app.services.folder_validator import (
    FolderValidationResult,
    SUPPORTED_EXTENSIONS,
    THIN_DOSSIER_THRESHOLD,
    missing_in_plain_words,
    score_evidence,
    score_rubric_labels,
    validate,
)
from app.ui import interview_screen, theme


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def _strength_color(score: int) -> str:
    if score >= 80:
        return "green"
    if score >= 60:
        return "blue"
    if score >= 40:
        return "orange"
    return "red"


def _reset_downstream() -> None:
    """Invalidate everything that depends on the dossier contents."""
    for key in (
        "dossier_chunks",
        "evidence_index",
        "canonical_profile",
        "evidence_index_meta",
        "extracted_job_fields",
    ):
        st.session_state[key] = None
    st.session_state.dossier_read = False
    # Whatever is built next comes from the folder, not from an earlier
    # interview. The interview's own answers are deliberately kept, so a user
    # who switches back to it carries on where they left off.
    st.session_state["profile_source"] = "dossier"
    # The interview publishes a strength score of its own, and until now
    # nothing ever cleared it. Left behind, it describes a profile that no
    # longer exists: it suppresses the gap-fill offer for a genuinely thin
    # folder (see _should_offer_gap_fill) and lets the analysis score this
    # folder's profile with the interview's number. The answers stay, so
    # resuming the interview publishes it again.
    st.session_state["interview_strength"] = None
    # Also drop any per-opportunity analysis (match/score/recommendation/
    # proposal/fingerprint) — it was built on the old evidence.
    clear_opportunity_state(st.session_state)


def _strength_tone(score: int) -> str:
    """The strength label's tone on the canvas's KPI tile.

    The thresholds are _strength_color's, unchanged — this only picks which of
    the design's bands paints the label.
    """
    if score >= 80:
        return "ok"
    if score >= 60:
        return "t2"
    if score >= 40:
        return "warn"
    return "stop"


def _render_validation_clean(result: FolderValidationResult, *, debug: bool) -> None:
    if result.issues and not result.exists:
        for issue in result.issues:
            st.error(issue)
        return

    # Normal UI shows ONLY the file count. The X/100 dossier-strength score,
    # its label, the "to strengthen your dossier consider adding…" line, and
    # the "evidence collection looks solid" banner mislead non-technical
    # users, so they are gated behind SHOW_DEBUG_PANEL=true.
    # Same numbers, same gating — rendered as the design canvas's KPI tiles.
    if debug:
        theme.kpis(
            [
                {"lab": "Dossier files", "val": result.total_files, "icon": "folder"},
                {
                    "lab": "Dossier strength",
                    "val": f"{result.strength_score}/100",
                    "icon": "spark",
                    "delta": result.strength_label,
                    "delta_kind": _strength_tone(result.strength_score),
                },
            ],
            columns=2,
        )
    else:
        theme.kpis(
            [{"lab": "Dossier files", "val": result.total_files, "icon": "folder"}],
            columns=1,
        )

    for issue in result.issues:
        st.error(issue)
    for warning in result.warnings:
        st.warning(warning)

    if debug and result.missing_categories:
        st.caption(
            "To strengthen your dossier, consider adding: "
            + ", ".join(result.missing_categories)
        )

    if (
        debug
        and result.can_continue
        and not result.warnings
        and not result.issues
        and result.strength_score >= 60
    ):
        st.success("Your evidence collection looks solid.")


def _render_debug_panel(result: FolderValidationResult | None) -> None:
    settings = get_settings()
    meta = st.session_state.get("evidence_index_meta") or {}
    proofs = st.session_state.get("evidence_index")
    with st.expander("Developer Debug Panel", expanded=False):
        st.markdown(
            f"**Provider:** `{settings.llm_provider}` • "
            f"**Model:** `{settings.active_model}`"
        )
        chunks = st.session_state.get("dossier_chunks")
        if st.session_state.get("dossier_read") and chunks is not None:
            summary = summarize_chunks(chunks)
            st.markdown(
                f"**Dossier read:** {summary.files_processed} file(s), "
                f"{summary.chunks_extracted} chunk(s), "
                f"{summary.failed_files} failed."
            )
            for f in summary.files:
                label = SOURCE_TYPE_LABELS.get(f.source_type, f.source_type)
                line = (
                    f"- `{f.file_path}` — {label} · status: **{f.status}** · "
                    f"chunks: **{f.chunk_count}**"
                )
                if f.warning:
                    line += f" · ⚠ {f.warning}"
                st.write(line)

        if proofs is not None and meta:
            st.markdown(
                f"**Evidence index source:** "
                + ("LLM API" if meta.get("used_api") else "local fallback")
            )
            if meta.get("error_message"):
                st.caption(f"Reason: {meta['error_message']}")
            claim_counts: dict[str, int] = {}
            for p in proofs:
                claim_counts[p.claim_type] = claim_counts.get(p.claim_type, 0) + 1
            if claim_counts:
                st.markdown("**Proof points by claim type:**")
                for claim_type, count in sorted(
                    claim_counts.items(), key=lambda kv: (-kv[1], kv[0])
                ):
                    st.write(f"- {claim_type}: **{count}**")

        if result is None:
            return

        if result.source_type_counts:
            st.markdown("**Source-type breakdown:**")
            for source_type, count in sorted(
                result.source_type_counts.items(), key=lambda kv: (-kv[1], kv[0])
            ):
                label = SOURCE_TYPE_LABELS.get(source_type, source_type)
                st.write(f"- {label}: **{count}**")

        labels = score_rubric_labels()
        if labels:
            st.markdown("**Score breakdown:**")
            for key, label in labels.items():
                awarded = result.score_breakdown.get(key, 0)
                st.write(f"- {label}: **{awarded}**")

        if result.files:
            st.markdown(f"**Files detected ({result.total_files}):**")
            for record in result.files:
                label = (
                    SOURCE_TYPE_LABELS.get(record.source_type, record.source_type)
                    if record.source_type
                    else "—"
                )
                icon = (
                    "✓"
                    if record.supported and record.readable
                    else ("⊘" if not record.supported else "✗")
                )
                st.write(f"{icon} `{record.relative_path}` — {label}")
            st.caption(
                "Supported extensions: " + ", ".join(sorted(SUPPORTED_EXTENSIONS))
            )


# ---------------------------------------------------------------------------
# Cloud (upload) mode
# ---------------------------------------------------------------------------
#
# On a desktop install the user points the app at a local folder. On a shared
# cloud deployment (e.g. a Hugging Face Space) there is no access to the
# visitor's machine, so they upload their files instead. The uploaded bytes are
# held in this session only. They are written to a private temp directory just
# while the existing ``validate → read_dossier → build_evidence_index`` pipeline
# runs against it unchanged, and that directory is deleted as soon as the read
# ends — the server's disk never keeps a visitor's files. Nothing about the
# downstream flow or look changes.


def is_cloud_mode() -> bool:
    """True when running on a shared host where local folder paths can't work.

    Detected from Hugging Face's ``SPACE_ID`` (set on every Space) or an
    explicit ``UPWORK_CLOUD`` override, so local desktop runs keep the original
    folder-path UI untouched.
    """
    return bool(os.getenv("SPACE_ID") or os.getenv("UPWORK_CLOUD"))


# Session keys for the persisted upload set. The records (name + bytes) are
# kept in session — NOT just in the file_uploader widget — because the widget
# returns an empty list after the user navigates to another step and back, so
# relying on it alone makes the dossier appear "lost". Kept until the page is
# reloaded (new session) or the user clears them. The widget only ever adds to
# them: whatever is dropped in joins the records and the widget re-mounts
# empty, so an uploader that came back empty is never taken for a smaller set.
# Files leave the set through their own Remove button or Remove all.
_UPLOAD_RECORDS_KEY = "dossier_uploaded_files"
_UPLOAD_SEQ_KEY = "dossier_uploader_seq"


def _upload_signature(records: list[dict]) -> tuple:
    """(name, size, content hash) per file — identifies an upload set."""
    return tuple(
        (r["name"], len(r["bytes"]), hashlib.sha256(r["bytes"]).hexdigest())
        for r in records
    )


def _materialize_records(records: list[dict]) -> str:
    """Write the persisted upload records into a new private temp dir.

    The directory lives under the OS temp location and is never committed or
    shared; the caller deletes it once the read is done (see
    :func:`_uploads_on_disk`). Returns the directory path for the standard
    folder pipeline.
    """
    base_path = Path(tempfile.mkdtemp(prefix="upwork_dossier_"))
    taken: set[str] = set()
    try:
        for r in records:
            safe_name = Path(r["name"]).name  # strip any directory components
            if not safe_name:
                continue
            # Two uploads can share a name (two "Final.pdf" from different
            # folders): the later one is written as "Final (2).pdf" instead of
            # overwriting the first. Compared case-blind, as macOS and Windows
            # disks compare names.
            name, n = safe_name, 1
            while name.casefold() in taken:
                n += 1
                name = f"{Path(safe_name).stem} ({n}){Path(safe_name).suffix}"
            taken.add(name.casefold())
            (base_path / name).write_bytes(r["bytes"])
    except BaseException:
        shutil.rmtree(base_path, ignore_errors=True)
        raise
    return str(base_path)


@contextmanager
def _uploads_on_disk(records: list[dict]):
    """Back ``dossier_folder_path`` with ``records`` for one pipeline run.

    The files are written to a new temp dir and the dir is deleted when the
    block ends, however it ends — including the ``st.rerun()`` the chain uses
    to move on. The bytes stay in session, so the next read simply writes them
    out again.
    """
    path = _materialize_records(records)
    st.session_state["dossier_folder_path"] = path
    try:
        yield path
    finally:
        shutil.rmtree(path, ignore_errors=True)
        st.session_state["dossier_folder_path"] = ""


def _forget_upload_reading() -> None:
    """The upload set changed: drop everything read from the previous one.

    On top of the evidence (:func:`_reset_downstream`), that is the folder
    validation — the gap-fill card quotes it, so it would go on describing
    files that are gone — the once-only gap-fill stop, so the new set gets
    its own offer, and a failed read's error, which would go on asking the
    user to replace files already replaced. ``_reset_downstream`` itself
    keeps all three, because the Validate and Continue paths call it right
    after validating.

    A profile the interview built was not read from these files alone,
    though. One built from the answers alone ("Interview me instead") never
    read them, so it stays exactly as it is. One that added the answers to
    them keeps the answers: it falls back to the answers alone, and the next
    Continue adds them to whatever files it reads.
    """
    st.session_state["dossier_validation"] = None
    st.session_state.pop(_THIN_OFFERED_KEY, None)
    st.session_state["dossier_read_error"] = False
    if st.session_state.get("profile_source") == "interview":
        meta = st.session_state.get("evidence_index_meta")
        if not (isinstance(meta, dict) and meta.get("with_folder")):
            return
        if interview_screen.rebuild_profile():
            # Still a gap fill, whichever button last opened the interview,
            # so the files read next get the answers added back.
            st.session_state["interview_entry"] = "gap_fill"
            return
    _reset_downstream()


def _sync_dossier_uploads() -> list[dict]:
    """Merge whatever was dropped into the uploader into the persisted set.

    * Dropped files join the stored records (a file already stored with the
      same name and content is not added twice) and invalidate downstream
      evidence; the widget then re-mounts empty. Nothing is written to disk
      here; the records go to disk only while they are read (see
      :func:`_uploads_on_disk`).
    * An empty uploader (e.g. after navigating away and back) keeps the stored
      records, so the dossier is never silently lost.

    Returns the current persisted records.
    """
    ss = st.session_state
    accepted = sorted(ext.lstrip(".") for ext in SUPPORTED_EXTENSIONS)
    uploader_key = f"dossier_uploads_{ss.get(_UPLOAD_SEQ_KEY, 0)}"
    files = st.file_uploader(
        "Upload your profile evidence",
        type=accepted,
        accept_multiple_files=True,
        key=uploader_key,
        help=(
            "Your Upwork Profile Optimisation document and your Dossier work "
            "best; add a portfolio, résumé or testimonials if you have them. "
            "Your files are processed in this session only and are never "
            "stored on the server."
        ),
    )
    st.caption(
        "Upload your **Upwork Profile Optimisation** document and your "
        "**Dossier**. Leave out the Offer Bank — it lists offers you didn't "
        "choose."
    )

    stored: list[dict] = ss.get(_UPLOAD_RECORDS_KEY) or []
    if files:
        known = set(_upload_signature(stored))
        added: list[dict] = []
        for f in files:
            record = {"name": f.name, "bytes": f.getvalue()}
            (identity,) = _upload_signature([record])
            if identity not in known:
                known.add(identity)
                added.append(record)
        if added:
            ss[_UPLOAD_RECORDS_KEY] = stored + added
            _forget_upload_reading()
        # Empty the widget: its files are in the stored set, listed below it.
        ss[_UPLOAD_SEQ_KEY] = ss.get(_UPLOAD_SEQ_KEY, 0) + 1
        st.rerun()
    return stored


def _remove_dossier_upload(index: int) -> None:
    """Remove one file from the persisted dossier upload set."""
    ss = st.session_state
    records = list(ss.get(_UPLOAD_RECORDS_KEY) or [])
    if 0 <= index < len(records):
        del records[index]
        ss[_UPLOAD_RECORDS_KEY] = records
        _forget_upload_reading()


def _clear_dossier_uploads() -> None:
    """Remove the persisted dossier upload set and reset the uploader widget."""
    ss = st.session_state
    ss[_UPLOAD_RECORDS_KEY] = []
    ss["dossier_folder_path"] = ""
    # Bump the uploader key so the widget itself re-mounts empty.
    ss[_UPLOAD_SEQ_KEY] = ss.get(_UPLOAD_SEQ_KEY, 0) + 1
    _forget_upload_reading()


def _card_upload_dossier(debug: bool) -> None:
    """Cloud variant of the dossier step: upload files, then continue.

    Mirrors the single-button normal flow — an uploader plus one *Continue to
    Job Screenshot* button that silently runs validate → read → index via
    :func:`_continue_chain`. In debug mode the granular read/index cards still
    render against the uploaded folder, exactly as on desktop.
    """
    with st.container(border=True, key="ups_panel_dossier_1"):
        theme.section_label(
            "Step 1 · Upload dossier files" if debug else "Upload dossier files"
        )
        stored = _sync_dossier_uploads()
        has_files = bool(stored)

        if has_files:
            # One row per stored file: the uploader above only adds.
            for index, record in enumerate(stored):
                col_name, col_remove = st.columns([3, 1])
                col_name.text(record["name"])
                if col_remove.button(
                    "Remove",
                    key=f"dossier_remove_upload_{index}",
                    use_container_width=True,
                    help="Remove just this file.",
                ):
                    _remove_dossier_upload(index)
                    st.rerun()
            col_ready, col_clear = st.columns([3, 1])
            col_ready.caption(f"{len(stored)} file(s) ready.")
            if col_clear.button(
                "Remove all",
                key="dossier_clear_uploads_btn",
                use_container_width=True,
                help="Clear these files so you can upload a different set.",
            ):
                _clear_dossier_uploads()
                st.rerun()

        if debug:
            # Validate against the uploaded folder so the file count / strength
            # panel works the same as the desktop debug flow.
            if st.button(
                "Validate Files",
                key="validate_folder_btn",
                disabled=not has_files,
                help="Upload at least one file first." if not has_files else None,
            ):
                with _uploads_on_disk(stored) as path:
                    st.session_state.dossier_validation = validate(path)
                _reset_downstream()
            result: FolderValidationResult | None = st.session_state.get(
                "dossier_validation"
            )
            if result is not None:
                _render_validation_clean(result, debug=debug)
            return

        if st.button(
            "Continue to Job Screenshot",
            type="primary",
            key="continue_to_screenshot_btn",
            disabled=not has_files,
            help="Upload at least one file first." if not has_files else None,
        ):
            # Each read gets a fresh temp folder, so the once-only thin-folder
            # stop remembers the files themselves rather than their path.
            with _uploads_on_disk(stored):
                _continue_chain(offer_key=_upload_signature(stored))
        elif not has_files:
            st.caption(
                "Upload your profile evidence files, then continue."
            )


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


def _card_select_folder(debug: bool) -> None:
    with st.container(border=True, key="ups_panel_dossier_2"):
        theme.section_label("Step 1 · Select dossier folder")
        st.text_input(
            "Dossier folder path",
            placeholder="/absolute/path/to/your/profile-evidence-folder",
            key="dossier_folder_path",
            help="Original files never leave your machine.",
        )
        path = (st.session_state.get("dossier_folder_path") or "").strip()
        if st.button(
            "Validate Folder",
            key="validate_folder_btn",
            disabled=not path,
            help="Enter a folder path first." if not path else None,
        ):
            st.session_state.dossier_validation = validate(path)
            _reset_downstream()

        result: FolderValidationResult | None = st.session_state.get(
            "dossier_validation"
        )
        if result is not None:
            _render_validation_clean(result, debug=debug)
        else:
            st.caption("After validation you'll see how many files were found.")


def _resolve_dossier_path(result: FolderValidationResult | None) -> str:
    """Folder path to read: prefer the typed path, fall back to validation."""
    path = (st.session_state.get("dossier_folder_path") or "").strip()
    if path:
        return path
    if result is not None and result.exists:
        return result.folder
    return ""


def _perform_read(path: str) -> None:
    """Read the dossier folder and persist the results into session state.

    A single bad file never aborts the read (the reader degrades it to a
    ``failed`` chunk), and an unexpected top-level failure leaves the user
    with a clean error rather than a crashed app.
    """
    try:
        chunks = read_dossier(path) if path else []
    except Exception:  # noqa: BLE001 - never crash the screen on a read error
        st.session_state.dossier_chunks = []
        st.session_state.dossier_read = False
        st.session_state.dossier_read_error = True
    else:
        st.session_state.dossier_chunks = chunks
        st.session_state.dossier_read = True
        st.session_state.dossier_read_error = False
    # A fresh read invalidates anything built from a previous read — and
    # anything an interview built: the profile now comes from this folder.
    st.session_state.evidence_index = None
    st.session_state.canonical_profile = None
    st.session_state.evidence_index_meta = None
    st.session_state["profile_source"] = "dossier"
    st.session_state["interview_strength"] = None
    clear_opportunity_state(st.session_state)


def _render_read_summary(summary: DossierReadSummary) -> None:
    """User-facing read result. No raw dossier text — counts only."""
    st.success("Dossier read successfully")
    col_files, col_chunks, col_failed = st.columns(3)
    col_files.metric("Files processed", summary.files_processed)
    col_chunks.metric("Chunks extracted", summary.chunks_extracted)
    col_failed.metric("Failed files", summary.failed_files)
    if summary.failed_files:
        st.warning("Some files could not be read, but the app continued.")
    st.caption("Profile evidence is held in this session only.")


def _card_read_evidence(cloud: bool = False) -> None:
    with st.container(border=True, key="ups_panel_dossier_3"):
        theme.section_label("Step 2 · Read profile evidence")
        result: FolderValidationResult | None = st.session_state.get(
            "dossier_validation"
        )
        can_read = bool(result and result.can_continue)

        if st.button(
            "Read Dossier",
            key="read_dossier_btn",
            disabled=not can_read,
            help=None if can_read else "Validate a folder first.",
        ):
            with st.spinner("Reading your profile evidence…"):
                if cloud:
                    # Uploads are on disk only while they are read.
                    records = st.session_state.get(_UPLOAD_RECORDS_KEY) or []
                    with _uploads_on_disk(records) as path:
                        _perform_read(path)
                else:
                    _perform_read(_resolve_dossier_path(result))

        # Rendered from session state (not just on click) so the summary
        # survives Streamlit reruns.
        if st.session_state.get("dossier_read_error"):
            st.error(
                "We couldn't read that folder. Re-validate the folder and "
                "try again."
            )

        chunks = st.session_state.get("dossier_chunks")
        dossier_read = bool(st.session_state.get("dossier_read"))

        if dossier_read and chunks is not None:
            _render_read_summary(summarize_chunks(chunks))

        st.divider()

        col_index, _ = st.columns(2)
        with col_index:
            can_build = bool(dossier_read and chunks)
            if st.button(
                "Create Evidence Index",
                key="build_evidence_btn",
                disabled=not can_build,
                help=None if can_build else "Read the dossier first.",
            ):
                proofs, profile, meta = build_evidence_index(chunks)
                st.session_state.evidence_index = proofs
                st.session_state.canonical_profile = profile
                st.session_state.evidence_index_meta = meta
                _score_read_files(proofs)

            proofs = st.session_state.get("evidence_index")
            if proofs:
                st.metric("Proof Points", len(proofs))
                st.caption("Evidence is ready for matching.")

        proofs = st.session_state.get("evidence_index")
        if proofs:
            st.divider()
            if st.button(
                "Continue to Job Screenshot",
                type="primary",
                key="continue_to_screenshot_btn",
            ):
                # Persist path so the app auto-reloads it on next restart.
                p = (st.session_state.get("dossier_folder_path") or "").strip()
                if p:
                    save_dossier_path(p)
                st.session_state.current_step = "screenshot"
                st.rerun()


# ---------------------------------------------------------------------------
# Normal-flow continue (runs validate → read → index silently)
# ---------------------------------------------------------------------------


def _score_read_files(proofs: list) -> None:
    """Re-score the folder from what its files turned out to hold.

    The validation runs before anything is read and sees file names only, so
    a full dossier PDF scored as thin. Scoring the proof points instead is
    what decides whether the "less than usual" offer appears.
    """
    result = st.session_state.get("dossier_validation")
    if result is not None and proofs:
        st.session_state.dossier_validation = score_evidence(result, proofs)


def _continue_chain(*, offer_key: object = None) -> None:
    """Run the full dossier pipeline silently, then advance.

    Wires the single normal-mode "Continue to Job Screenshot" button to the
    backend chain in order — ``validate()`` → ``read_dossier()`` →
    ``create_evidence_index()`` — behind one spinner, so a non-technical
    user never sees the intermediate Validate / Read / Index steps. The
    pipeline order is unchanged; only the on-screen surface collapsed to one
    action.

    A folder that can't be validated (bad path, empty folder, or no readable
    files) — or a read that yields nothing — stops the chain: the user stays
    on the page and sees one clean error, never a stack trace.

    ``offer_key`` is what the once-only thin-folder stop remembers: the
    folder path unless the caller names something steadier (the cloud
    uploader passes its upload signature).

    A profile that is the folder plus a gap-filling interview is read back
    with the interview in it. The read alone builds the profile from the
    files, and the answers would drop out of it without a word.
    """
    path = (st.session_state.get("dossier_folder_path") or "").strip()
    if offer_key is None:
        offer_key = path
    # Taken before the reset below clears what they are read from.
    was_interview = st.session_state.get("profile_source") == "interview"
    keep_interview = interview_screen.adds_to_folder()
    with st.spinner("Preparing your profile evidence…"):
        # 1. Validate the typed folder. A re-run invalidates any evidence
        #    built from a previously selected folder.
        result = validate(path) if path else None
        st.session_state.dossier_validation = result
        _reset_downstream()
        # 2. Read + 3. build the evidence index only when the folder is usable.
        if result is not None and result.can_continue:
            _perform_read(path)
            chunks = st.session_state.get("dossier_chunks")
            if chunks:
                proofs, profile, meta = build_evidence_index(chunks)
                st.session_state.evidence_index = proofs
                st.session_state.canonical_profile = profile
                st.session_state.evidence_index_meta = meta
                _score_read_files(proofs)
                if keep_interview:
                    interview_screen.rebuild_profile(chunks)
    if was_interview and st.session_state.get("profile_source") != "interview":
        # The folder has taken the interview's place, so the answers are no
        # longer in the profile: a thin folder gets its offer again rather
        # than going on as though they were.
        st.session_state.pop(_THIN_OFFERED_KEY, None)
    if st.session_state.get("evidence_index"):
        # Persist the path so the app can auto-reload it on the next restart.
        if path:
            save_dossier_path(path)
        # A thin folder stops here once, because the offer to fill its gaps
        # is only drawn on this screen. Pressing Continue again on the same
        # folder (or the same uploaded files) goes on, so the offer can never
        # become a loop.
        if (
            interview_screen.is_available()
            and _should_offer_gap_fill(result)
            and st.session_state.get(_THIN_OFFERED_KEY) != offer_key
        ):
            st.session_state[_THIN_OFFERED_KEY] = offer_key
            st.rerun()
        st.session_state.current_step = "screenshot"
        st.rerun()
    else:
        st.error(_no_profile_message(result))


# What the cloud screen says when the uploaded files could not be read at all:
# it has an uploader, not a path to check.
_UPLOADS_UNREADABLE = (
    "Couldn't read your uploaded files. Remove them and upload them again."
)

# A file the reader opened but took no text from: a scanned PDF's pages come
# back "empty", and an image is kept as metadata only, because nothing here
# runs OCR.
_NO_TEXT_STATUSES = ("empty", "metadata_only")


def _no_profile_message(result: FolderValidationResult | None) -> str:
    """Why Continue built no profile, in words the user can act on.

    Only a desktop folder has a path to check. Files that were read but gave
    no text — a scanned résumé, a photo of one — are named, because checking
    the path or uploading them again would never change them.
    """
    cloud = is_cloud_mode()
    interview_hint = (
        ", or answer a few questions above instead"
        if interview_screen.is_available()
        else ""
    )
    chunks = st.session_state.get("dossier_chunks") or []
    if (
        result is None
        or not result.can_continue
        or st.session_state.get("dossier_read_error")
        or not chunks
    ):
        if cloud:
            return _UPLOADS_UNREADABLE
        return "Couldn't read that folder. Check the path and try again."

    # Names go in as code, so Markdown never reads a file name as formatting.
    files = summarize_chunks(chunks).files
    no_text = [f"`{f.file_name}`" for f in files if f.status in _NO_TEXT_STATUSES]
    broken = [f"`{f.file_name}`" for f in files if f.status == "failed"]
    where = "" if cloud else " to the folder"
    add = "Upload" if cloud else "Add"
    if not (no_text or broken):
        return (
            "We read your files but found no work in them to quote from. "
            f"{add} your résumé, portfolio or testimonials{where}"
            f"{interview_hint}."
        )
    message = ""
    if no_text:
        message += (
            f"{_join_words(no_text)} {'has' if len(no_text) == 1 else 'have'} "
            "no text the app can read: scanned pages and photos aren't read. "
        )
    if broken:
        message += f"{_join_words(broken)} couldn't be opened. "
    return (
        message
        + f"{add} a PDF with selectable text, a Word file or a text file{where}"
        + f"{interview_hint}."
    )


def _card_continue_normal() -> None:
    """Single-button dossier card for the non-technical flow.

    One text box + one "Continue to Job Screenshot" button. The button runs
    the whole backend chain silently behind a spinner — ``validate()`` →
    ``read_dossier()`` → ``create_evidence_index()`` — then advances. There
    is no file count, no strength score, and no separate Validate / Read /
    Index buttons; those are all debug-only.
    """
    # Pre-fill the text input with the persisted path so the user
    # sees their last folder already filled in if they land here again.
    from app.config import get_saved_dossier_path
    if not st.session_state.get("dossier_folder_path"):
        saved = get_saved_dossier_path()
        if saved:
            st.session_state["dossier_folder_path"] = saved

    with st.container(border=True, key="ups_panel_dossier_4"):
        theme.section_label("Select dossier folder")
        st.text_input(
            "Dossier folder path",
            placeholder="/absolute/path/to/your/profile-evidence-folder",
            key="dossier_folder_path",
            help="Original files never leave your machine.",
        )
        path = (st.session_state.get("dossier_folder_path") or "").strip()
        # The single button runs validate + read + index, then advances (or,
        # on failure, leaves a clean inline error via _continue_chain).
        if st.button(
            "Continue to Job Screenshot",
            type="primary",
            key="continue_to_screenshot_btn",
            disabled=not path,
            help="Enter a folder path first." if not path else None,
        ):
            _continue_chain()
        else:
            st.caption(
                "Point to a local folder of your profile evidence, then continue."
            )


# ---------------------------------------------------------------------------
# The two ways into a profile
# ---------------------------------------------------------------------------
#
# The folder route below is untouched: same cards, same single button, same
# backend chain. These two cards only add the second route for users who have
# no files to hand, and for users whose files turned out to be thin.


# The folder (or, on the cloud uploader, the upload set) whose thin score was
# last shown the fill-the-gaps offer.
_THIN_OFFERED_KEY = "dossier_thin_offered"


def _goto_interview(entry: str = "chooser") -> None:
    # Both ways in land on the interview's intro card, where the AI toggle
    # and "Start over" live. Without this the flag set by an earlier visit
    # would drop the user straight back onto the live question with both
    # controls out of reach. Answers are kept: with an interview already in
    # progress the card's own button reads "Resume the interview".
    interview_screen.show_intro_on_entry()
    # "chooser" is "Interview me instead": the interview replaces a folder
    # read earlier. "gap_fill" adds the interview to the folder.
    st.session_state["interview_entry"] = entry
    st.session_state.current_step = "interview"
    st.rerun()


def _card_choose_path(cloud: bool) -> None:
    """Offer the interview alongside the folder, before the folder cards."""
    with st.container(border=True, key="ups_panel_dossier_5"):
        theme.section_label("Two ways to build your profile")
        col_files, col_talk = st.columns(2)
        with col_files:
            st.markdown("**Use your own work**")
            st.caption(
                "Upload your files below."
                if cloud
                else "Point the app at your folder below."
            )
            theme.html(theme.tag("Best grounding", "ok"))
        with col_talk:
            st.markdown("**Answer a few questions**")
            st.caption(
                "Nothing to upload? The app interviews you and builds the "
                "same profile from your answers."
            )
            if st.button(
                "Interview me instead",
                key="start_interview_btn",
                use_container_width=True,
            ):
                _goto_interview("chooser")


def _card_interview_gap_fill(result: FolderValidationResult, *, debug: bool) -> None:
    """Offer the interview as a gap-filler for a thin dossier."""
    with st.container(border=True, key="ups_panel_dossier_6"):
        theme.section_label("Your files gave us less than usual")
        missing = missing_in_plain_words(result)
        st.warning(
            "We read your files but couldn't find "
            + (_join_words(missing) if missing else "much to quote from")
            + ". A few questions about your work fill the gaps — your files "
            "are kept either way."
        )
        if debug:
            st.caption(
                f"Dossier strength {result.strength_score}/100 "
                f"(below {THIN_DOSSIER_THRESHOLD})."
            )
        col_fill, col_go = st.columns([2, 1])
        fill = col_fill.button(
            "Fill the gaps with a few questions",
            type="primary",
            key="gap_fill_interview_btn",
            use_container_width=True,
        )
        go_on = col_go.button(
            "Continue with my files",
            key="continue_thin_folder_btn",
            use_container_width=True,
            disabled=not st.session_state.get("evidence_index"),
            help=(
                "Go on to the job post with the profile built from your files."
                if st.session_state.get("evidence_index")
                else "Read your folder first."
            ),
        )
        if fill:
            _goto_interview("gap_fill")
        if go_on:
            st.session_state.current_step = "screenshot"
            st.rerun()


def _join_words(items: list[str]) -> str:
    """Join phrases as a sentence would: "a", "a and b", "a, b and c"."""
    if len(items) <= 1:
        return "".join(items)
    return ", ".join(items[:-1]) + " and " + items[-1]


def _should_offer_gap_fill(result: FolderValidationResult | None) -> bool:
    """True when real files were read but they scored thin.

    ``can_continue`` is what separates a real folder from the placeholder
    result the interview leaves behind, so an interview-built profile is never
    told its files were disappointing.

    The validation is a reading of the folder and nothing else: it keeps its
    thin score after a gap-filling interview has already answered for it. So
    once the interview has built the profile, or has published a strength of
    its own, the offer stops — otherwise "Your files gave us less than usual"
    greets the user on every later visit to a gap they have already filled.
    """
    if result is None or not result.can_continue:
        return False
    if st.session_state.get("profile_source") == "interview":
        return False
    if st.session_state.get("interview_strength") is not None:
        return False
    return int(getattr(result, "strength_score", 0) or 0) < THIN_DOSSIER_THRESHOLD


# ---------------------------------------------------------------------------
# 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_dossier"):
            st.session_state.current_step = "setup"
            st.rerun()
        return

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

    cloud = is_cloud_mode()
    intro = (
        "Upload your real work — portfolio, résumé, testimonials, past "
        "proposals. Every claim is grounded in <b>these files only</b>."
        if cloud
        else "Point the app at a folder of your real work — portfolio, résumé, "
        "testimonials, past proposals. Every claim is grounded in <b>these files only</b>."
    )
    theme.screen_head("dossier", "Your work dossier", intro)

    # If the smart-landing auto-load failed (folder moved / deleted), show a
    # clear error so the user knows to update the path — no traceback. The
    # cloud screen has no path, only uploads that failed to read.
    if st.session_state.get("dossier_read_error") and not st.session_state.get("dossier_read"):
        st.error(
            _UPLOADS_UNREADABLE
            if cloud
            else "Your saved dossier folder could not be found or read. "
            "Please enter the correct path below and continue."
        )

    validation: FolderValidationResult | None = st.session_state.get(
        "dossier_validation"
    )
    if interview_screen.is_available():
        if _should_offer_gap_fill(validation):
            _card_interview_gap_fill(validation, debug=debug)
        else:
            _card_choose_path(cloud)

    if debug:
        # Developer/admin mode keeps the granular Validate / Read Dossier /
        # Create Evidence Index buttons, the file count, strength score,
        # chunk/proof-point stats, and the debug panel. The first card swaps to
        # an uploader in cloud mode; everything downstream is identical.
        if cloud:
            _card_upload_dossier(debug)
        else:
            _card_select_folder(debug)
        _card_read_evidence(cloud)
        _render_debug_panel(st.session_state.get("dossier_validation"))
    elif cloud:
        # Cloud normal mode: one uploader + one button. The button silently
        # runs validate → read → index and advances, just like desktop.
        _card_upload_dossier(debug)
    else:
        # Desktop normal mode: one text box + one button. The button silently
        # runs validate → read → index and lands the user on the Job Screenshot
        # step (no file count, no strength score, no extra buttons).
        _card_continue_normal()