File size: 40,280 Bytes
48d9178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1428c4
48d9178
 
 
 
 
2e740d5
 
48d9178
2e740d5
48d9178
2e740d5
 
48d9178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1428c4
 
 
 
 
 
48d9178
 
e1428c4
 
48d9178
 
 
e1428c4
 
 
 
48d9178
 
 
 
 
 
 
 
 
e1428c4
 
48d9178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e740d5
48d9178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
r"""
IL CMS Tagger β€” Excel template generator
----------------------------------------
Standalone tool. Opens the IL CMS Create/Edit Question form with Playwright
(reusing a saved CMS session) and writes a ready-to-fill tagging template
(tagging_template.xlsx) with one column for EVERY field on the form, across all
three tabs:

  Learning Outcomes : Subject, Chapter, Topic, Subtopic, Minitopic, Micro topic
  Exam Details      : TOC, Grade
  Other Details     : Objective, Difficulty Level, Bloom Taxonomy, Relevance,
                      Concept Level, Source, Syllabus, Author, Tags,
                      Exam, Year, Month, Date

For each flat-list dropdown the live options are scraped and turned into an
in-Excel dropdown (data validation). Cascade dropdowns (Chapter / Topic /
Subtopic / Minitopic / Micro topic β€” options depend on the prior pick), plus
multi-select / date / free-text fields (Author, Tags, Date), are left as plain
columns so you can type freely.

Usage
    python make_template.py                  # auto-pick newest saved session
    python make_template.py --qid ILQ-2344120  # open this question's Edit form
    python make_template.py --state path\to\state.json --out my_template.xlsx
    python make_template.py --no-scrape      # skip CMS, use built-in defaults
    python make_template.py --headed         # watch the browser (default: headed)

Why a question id helps: the surest way to reveal the dropdowns is to open an
existing question's "Edit Details" form. Pass any real question id you can see
in the bank with --qid. Without it the script tries a "Create Question" button,
and if that isn't found it still writes the template from the built-in lists.

Scraped values always win; the built-in lists only fill fields that couldn't be
read (e.g. a tab that failed to open). Re-run whenever the CMS taxonomy changes.
"""

import argparse
import glob
import os
import sys
import threading

from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.datavalidation import DataValidation

import il_endpoints

BASE_DIR   = os.path.dirname(os.path.abspath(__file__))
DATA_DIR   = os.path.join(os.path.dirname(BASE_DIR), "database")
STATE_FILE = os.path.join(BASE_DIR, "state.json")
STATE_DIR  = os.path.join(DATA_DIR, "tagger_sessions")
URL        = il_endpoints.QUESTION_BANK_URL

# Subject β†’ Chapter β†’ Topic β†’ Sub-Topic taxonomy used to build the cascading
# (dependent) Excel dropdowns. Two offline sources are merged so all five subjects
# have a full cascade:
#   * JEE TOC CSV  β†’ Physics / Mathematics / Chemistry
#   * Biology xlsx β†’ Botany / Zoology  (cols SUBJECTNAME/CHAPTERNAME/TOPICNAME/SUBTOPICNAME)
TAXONOMY_CSV = r"C:\Users\admin\Downloads\JEE MAIN TOC (1).csv"
TAX_ENCODING = "cp1252"
BIO_TOC_XLSX = r"C:\Users\admin\Downloads\Biology TOC.xlsx"
SUBJECT_LIST = ["Physics", "Chemistry", "Mathematics", "Botany", "Zoology"]

# ── Template layout ───────────────────────────────────────────────────────────
# Every field on the CMS Create-Question form, in tab order, becomes a column.
#   mode "scrape" : a flat-list ng-select β€” we read its options and add an
#                   in-Excel dropdown (data validation).
#   mode "free"   : cascade / multi-select / date / free-text β€” plain column, no
#                   dropdown (its options depend on prior picks or aren't a list).
#   tab           : which CMS tab the field lives on (None = no tab switch)
#   placeholders  : ng-select placeholder texts to try when opening it
#   label         : the on-screen field label (used as a locator fallback)
#   for_attr      : label[for=] fallback (works when a value is already selected)
#   default       : built-in list used only when scraping can't read the field
TRACKING_COLS = ["Status", "Run Details", "Attempts", "Last Worker", "Last Updated"]

FIELDS = [
    # ── Learning Outcomes ──────────────────────────────────────────────────────
    {"col": "subject",     "label": "Subject",     "tab": "Learning Outcomes", "mode": "scrape",
     "placeholders": ["Select Subject"], "for_attr": "Subject",
     "default": ["Physics", "Chemistry", "Biology", "Mathematics"]},
    {"col": "chapter",     "label": "Chapter",     "tab": "Learning Outcomes", "mode": "free"},
    {"col": "topic",       "label": "Topic",       "tab": "Learning Outcomes", "mode": "free"},
    {"col": "subtopic",    "label": "Subtopic",    "tab": "Learning Outcomes", "mode": "free"},
    {"col": "minitopic",   "label": "Minitopic",   "tab": "Learning Outcomes", "mode": "free"},
    {"col": "micro_topic", "label": "Micro topic", "tab": "Learning Outcomes", "mode": "free"},
    # ── Exam Details ───────────────────────────────────────────────────────────
    {"col": "toc",   "label": "TOC",   "tab": "Exam Details", "mode": "scrape",
     "placeholders": ["Select TOC"]},
    {"col": "grade", "label": "Grade", "tab": "Exam Details", "mode": "scrape",
     "placeholders": ["Select Grade"], "default": ["Grade 11", "Grade 12"]},
    # ── Other Details ──────────────────────────────────────────────────────────
    {"col": "objective",      "label": "Objective",       "tab": "Other Details", "mode": "scrape",
     "placeholders": ["Select Objective"], "for_attr": "objective",
     "default": ["Formula Based", "Theory", "Multi-Concept", "Real-Life Example", "Extrapolation"]},
    {"col": "difficulty",     "label": "Difficulty Level", "tab": "Other Details", "mode": "scrape",
     "placeholders": ["Select Difficulty Level", "Select Difficulty"], "for_attr": "difficultyLevel",
     "default": ["easy", "moderate", "difficult", "very difficult"]},
    {"col": "bloom_taxonomy", "label": "Bloom Taxonomy",  "tab": "Other Details", "mode": "scrape",
     "placeholders": ["Select Bloom Taxonomy", "Select Bloom"], "for_attr": "bloomTaxonomy",
     "default": ["Knowledge", "Understanding (Comprehension)", "Application",
                 "Analysis (compare, contrast, categorize, identify)"]},
    {"col": "relevance",      "label": "Relevence",       "tab": "Other Details", "mode": "scrape",
     "placeholders": ["Select Relevence", "Select Relevance"], "for_attr": "relevence",  # CMS typo
     "default": ["Relevant to NEET"]},
    {"col": "concept_level",  "label": "Concept Level",   "tab": "Other Details", "mode": "scrape",
     "placeholders": ["Select Concept Level"]},
    {"col": "source",         "label": "Source",          "tab": "Other Details", "mode": "scrape",
     "placeholders": ["Select Source"]},
    {"col": "syllabus",       "label": "Syllabus",        "tab": "Other Details", "mode": "scrape",
     "placeholders": ["Select Syllabus"]},
    {"col": "author",         "label": "Author",          "tab": "Other Details", "mode": "free"},
    {"col": "tags",           "label": "Tags",            "tab": "Other Details", "mode": "free"},
    {"col": "exam",           "label": "Exam",            "tab": "Other Details", "mode": "scrape",
     "placeholders": ["Select Exam"]},
    {"col": "year",           "label": "Year",            "tab": "Other Details", "mode": "scrape",
     "placeholders": ["Select Year"]},
    {"col": "month",          "label": "Month",           "tab": "Other Details", "mode": "scrape",
     "placeholders": ["Select Month"],
     "default": ["January", "February", "March", "April", "May", "June", "July",
                 "August", "September", "October", "November", "December"]},
    {"col": "date",           "label": "Date",            "tab": "Other Details", "mode": "free"},
]

SCRAPE_FIELDS = [f for f in FIELDS if f["mode"] == "scrape"]

# Lists longer than this aren't turned into a dropdown (e.g. huge Author/Tag
# lists) β€” they'd bloat the file and overwhelm the picker; the column stays free.
MAX_DROPDOWN_OPTIONS = 500

COLUMN_ORDER = ["question_id"] + [f["col"] for f in FIELDS] + TRACKING_COLS

# Illustrative rows for the sample workbook. The Physics paths are real taxonomy
# entries so the cascade dropdowns show them as valid picks; the Botany row shows
# what a row looks like for a subject that has no offline cascade data yet.
EXAMPLE_ROWS = [
    {"question_id": "ILQ-2344120", "subject": "Physics", "chapter": "Motion in a Straight Line",
     "topic": "Kinematic equations for uniformly accelerated motion", "subtopic": "Motion in Horizontal Plane",
     "grade": "Grade 11", "objective": "Formula Based", "difficulty": "moderate",
     "bloom_taxonomy": "Application", "relevance": "Relevant to NEET", "Status": "unprocessed"},
    {"question_id": "ILQ-2344125", "subject": "Physics", "chapter": "Motion in a Straight Line",
     "topic": "Kinematic equations for uniformly accelerated motion", "subtopic": "Motion under gravity",
     "grade": "Grade 11", "objective": "Multi-Concept", "difficulty": "difficult",
     "bloom_taxonomy": "Application", "relevance": "Relevant to NEET", "Status": "unprocessed"},
    {"question_id": "ILQ-2344127", "subject": "Physics", "chapter": "Laws of Motion",
     "topic": "Newton's second law of motion", "subtopic": "Impulse & its Applications",
     "grade": "Grade 11", "objective": "Formula Based", "difficulty": "moderate",
     "bloom_taxonomy": "Application", "relevance": "Relevant to NEET", "Status": "unprocessed"},
    {"question_id": "ILQ-2344153", "subject": "Physics", "chapter": "Kinetic Theory",
     "topic": "Kinetic theory of an ideal gas", "subtopic": "RMS Speed",
     "grade": "Grade 11", "objective": "Theory", "difficulty": "moderate",
     "bloom_taxonomy": "Understanding (Comprehension)", "relevance": "Relevant to NEET", "Status": "unprocessed"},
    {"question_id": "ILQ-2400001", "subject": "Botany", "chapter": "Cell: The Unit of Life",
     "topic": "Cell theory and cell organelles", "subtopic": "Mitochondria",
     "grade": "Grade 11", "objective": "Theory", "difficulty": "easy",
     "bloom_taxonomy": "Analysis (compare, contrast, categorize, identify)",
     "relevance": "Relevant to NEET", "Status": "unprocessed"},
]


# ── Session discovery ─────────────────────────────────────────────────────────

def pick_state_file(explicit):
    """Resolve which Playwright storage_state to use."""
    if explicit:
        if not os.path.exists(explicit):
            sys.exit(f"State file not found: {explicit}")
        return explicit
    candidates = sorted(glob.glob(os.path.join(STATE_DIR, "state_*.json")),
                        key=os.path.getmtime, reverse=True)
    if candidates:
        return candidates[0]
    if os.path.exists(STATE_FILE):
        return STATE_FILE
    return None


# ── Scraping ──────────────────────────────────────────────────────────────────

def scrape_options(state_file, qid, headless):
    """Open the CMS form and return {col: [options]} for every field we could read."""
    from playwright.sync_api import sync_playwright
    from playwright.sync_api import TimeoutError as PWTimeout

    QID_SELECTOR = "input[formcontrolname='searchById'], input[placeholder*='Question ID']"
    found = {}

    def wait(page, ms=800):
        page.wait_for_timeout(ms)

    def first_visible(locator):
        for i in range(locator.count()):
            item = locator.nth(i)
            try:
                if item.is_visible():
                    return item
            except Exception:
                continue
        return None

    def maybe_click(page, texts, exact=False):
        for text in texts:
            for loc in [
                page.get_by_role("button", name=text, exact=exact),
                page.get_by_text(text, exact=exact),
                page.locator(f"text={text}"),
                page.locator(f"button:has-text('{text}')"),
            ]:
                target = first_visible(loc)
                if target:
                    try:
                        target.scroll_into_view_if_needed()
                        target.click()
                        return True
                    except Exception:
                        continue
        return False

    def open_dropdown(page, field):
        """Click a field's arrow so its ng-dropdown-panel opens. Returns True/False."""
        cands = []
        for ph in field.get("placeholders", []):
            cands += [
                page.locator(f"div[role='dialog'] ng-select:has(.ng-placeholder:text-is('{ph}')) .ng-arrow-wrapper"),
                page.locator(f"ng-select:has(.ng-placeholder:text-is('{ph}')) .ng-arrow-wrapper"),
                page.locator(f"ng-select[placeholder='{ph}'] .ng-arrow-wrapper"),
            ]
        if field.get("for_attr"):
            cands.append(page.locator(
                f".form-group:has(label[for='{field['for_attr']}']) .ng-arrow-wrapper"))
        if field.get("label"):
            # Last resort: the ng-select that follows a label carrying this text.
            cands.append(page.locator(
                f"label:has-text('{field['label']}')"
            ).locator("xpath=following::ng-select[1]//*[contains(@class,'ng-arrow-wrapper')]"))
        for cand in cands:
            target = first_visible(cand)
            if target is None:
                continue
            try:
                target.scroll_into_view_if_needed()
                target.click()
                wait(page, 700)
                if page.locator(".ng-dropdown-panel .ng-option").count() > 0:
                    return True
                # opened but empty β€” close and try next candidate
                page.keyboard.press("Escape")
            except Exception:
                try:
                    page.keyboard.press("Escape")
                except Exception:
                    pass
        return False

    def read_open_options(page):
        opts = page.locator(".ng-dropdown-panel .ng-option")
        out, seen = [], set()
        for i in range(opts.count()):
            try:
                txt = opts.nth(i).inner_text().strip()
            except Exception:
                continue
            if not txt or txt.lower() == "no items found":
                continue
            if txt not in seen:
                seen.add(txt)
                out.append(txt)
        try:
            page.keyboard.press("Escape")
        except Exception:
            pass
        wait(page, 300)
        return out

    def open_form(page):
        """Reveal the Create/Edit Question form. Returns the page that has the form."""
        # Path A β€” open an existing question's Edit Details (most reliable).
        if qid:
            try:
                page.wait_for_load_state("networkidle", timeout=15000)
            except Exception:
                pass
            for _ in range(5):
                box = page.locator(QID_SELECTOR)
                if box.count() and box.first.is_visible():
                    break
                maybe_click(page, ["Filter"])
                wait(page, 2000)
            box = page.locator(QID_SELECTOR)
            if box.count() and box.first.is_visible():
                try:
                    box.first.fill(qid)
                except Exception:
                    pass
                maybe_click(page, ["Save", "Apply"])
                wait(page, 3000)
                links = page.locator("a")
                for i in range(links.count()):
                    link = links.nth(i)
                    try:
                        if qid not in link.inner_text():
                            continue
                        with page.context.expect_page(timeout=3000) as new_info:
                            link.click()
                        np = new_info.value
                        np.wait_for_load_state()
                        page = np
                        break
                    except PWTimeout:
                        try:
                            link.click()
                            page.wait_for_load_state("networkidle", timeout=8000)
                        except Exception:
                            continue
                    except Exception:
                        continue
                wait(page, 3000)
                unapprove = first_visible(page.locator("button:has-text('Unapprove')"))
                if unapprove:
                    try:
                        unapprove.click()
                        wait(page, 1000)
                        ok = first_visible(page.locator(
                            ".modal-content button.btn-success, .modal-content button:has-text('Submit')"))
                        if ok:
                            ok.click()
                        wait(page, 3000)
                    except Exception:
                        pass
                for _ in range(2):
                    if maybe_click(page, ["Edit Details"]):
                        break
                    wait(page, 2000)
                wait(page, 2500)
                return page
        # Path B β€” try a Create Question button.
        if maybe_click(page, ["Create Question", "Add Question", "Create", "Add"]):
            wait(page, 2500)
        return page

    with sync_playwright() as pw:
        browser = pw.chromium.launch(headless=headless, slow_mo=120)
        context = (browser.new_context(storage_state=state_file)
                   if state_file and os.path.exists(state_file)
                   else browser.new_context())
        page = context.new_page()
        page.goto(URL)
        wait(page, 3000)
        if "/login" in page.url:
            browser.close()
            raise RuntimeError("CMS session is not logged in (redirected to /login). "
                               "Set up / refresh the CMS login first.")

        page = open_form(page)

        current_tab = None
        for field in SCRAPE_FIELDS:
            tab = field["tab"]
            if tab and tab != current_tab:
                maybe_click(page, [tab])
                wait(page, 900)
                current_tab = tab
            try:
                if open_dropdown(page, field):
                    opts = read_open_options(page)
                    if opts:
                        found[field["col"]] = opts
                        print(f"  scraped {field['col']:<14} {len(opts)} option(s)")
                    else:
                        print(f"  WARN  {field['col']:<14} dropdown opened but no options")
                else:
                    print(f"  WARN  {field['col']:<14} could not open dropdown")
            except Exception as e:
                print(f"  WARN  {field['col']:<14} {e}")

        browser.close()
    return found


# ── Other-Details options from the CMS /lookups API (no browser) ──────────────

# Which Other-Details column is filled from which /lookups code. Values are the
# exact option NAMES the tagger (push_tags) resolves back to UUIDs, so a pick from
# these dropdowns is guaranteed to tag cleanly.
LOOKUP_CODE_FOR_COL = {
    "objective": "OBJECTIVE", "bloom_taxonomy": "TAXONOMY", "relevance": "RELEVANCE",
    "concept_level": "TEST_LEVEL", "source": "SOURCE", "syllabus": "SYLLABUS",
}


# The lookup options are tenant/token-bound UUIDs, and /tag/prep + /tag/apply call
# lookups_options() back-to-back β€” fetch once per QB token per process.
_lookups_cache = {}
_lookups_lock = threading.Lock()


def lookups_options(state_file):
    """Return {col: [option names]} for the lookup-backed Other-Details fields,
    fetched from the QB /lookups API using a saved CMS session (no Playwright).
    Cached per QB token."""
    sys.path.insert(0, os.path.join(BASE_DIR, "ai_tagger"))
    import push_tags as pt
    h = pt.qb_headers_from_state(state_file)
    token = h["authorization"]
    with _lookups_lock:
        if token in _lookups_cache:
            return _lookups_cache[token]
    codes = sorted(set(LOOKUP_CODE_FOR_COL.values()))
    r = pt.SESSION.post(f"{pt.QB}/lookups", json=codes, headers=h, timeout=30)
    r.raise_for_status()
    by_code = {x["lookupcode"]: [v["name"] for v in x.get("lookupvalues", [])]
               for x in r.json().get("data", [])}
    out = {}
    for col, code in LOOKUP_CODE_FOR_COL.items():
        if by_code.get(code):
            out[col] = by_code[code]
    with _lookups_lock:
        _lookups_cache[token] = out
    return out


# ── live Subjectβ†’Chapterβ†’Topicβ†’Subtopic taxonomy from the CMS community API ────

# Grade-tree subject ROOT node ids (the "Master TOC" roots the tagger resolves
# against). Same map as push_tags.SUBJECT_ID.
CMS_SUBJECT_ROOT = {"physics": 1, "chemistry": 2, "mathematics": 3,
                    "botany": 4, "zoology": 5}
CMS_GRADES = (11, 12)

# Exam β†’ subject list mapping (used to filter cascading dropdowns by selected TOC).
# Key matches the pill data-toc attribute sent from the tagger page.
EXAM_SUBJECTS = {
    "JEE Main":      ["Physics", "Chemistry", "Mathematics"],
    "JEE Advanced":  ["Physics", "Chemistry", "Mathematics"],
    "NEET":          ["Physics", "Chemistry", "Botany", "Zoology"],
    "EAPCET":        ["Physics", "Chemistry", "Mathematics"],
    "KCET":          ["Physics", "Chemistry", "Mathematics"],
}


def cms_taxonomy(subjects=None, grades=CMS_GRADES, log=print):
    """Build {subject: {chapter: {topic: [subtopics]}}} live from the community
    node API (extract_toc), instead of the offline CSV/xlsx. One bulk call per
    level (children carry parentNodeId, so a whole level resolves at once);
    grades are merged by name. Needs a community-valid token."""
    from collections import OrderedDict
    sys.path.insert(0, os.path.join(BASE_DIR, "ai_tagger"))
    import extract_toc as toc
    try:
        toc._ensure_session()
        # verify the saved token actually passes the community API; if not, log in
        if not toc._token_works_for_community(toc._SESSION.get("token")):
            toc.fetch_token_via_login(log_cb=lambda m: log(f"  [community] {m}"))
    except Exception:
        toc.fetch_token_via_login(log_cb=lambda m: log(f"  [community] {m}"))

    def bulk_children(parent_ids, grade, chunk=200):
        """[(child_id, child_name, parent_id)] for every parent, one call/chunk."""
        ids, out = [int(x) for x in parent_ids], []
        for i in range(0, len(ids), chunk):
            body = {"nodeIds": ids[i:i + chunk], "status": "active",
                    "gradeIds": [int(grade)]}
            data = toc._community_get("/node/get_nodes_under_nodes_grades",
                                      json_body=body, method="POST")
            for n in data.get("data", {}).get("nodes_grades_list", []):
                out.append((n["nodeId"], n["nodeName"], n.get("parentNodeId")))
        return out

    subjects = subjects or SUBJECT_LIST
    tree = OrderedDict()
    for s in subjects:
        root = CMS_SUBJECT_ROOT.get(s.lower())
        if not root:
            log(f"  {s:<12} no subject root id β€” skipped")
            continue
        stree = tree.setdefault(s, OrderedDict())
        for g in grades:
            chaps = bulk_children([root], g)
            chap_name = {cid: nm for cid, nm, _ in chaps}
            if not chap_name:
                continue
            tops = bulk_children(list(chap_name), g)
            top_name   = {tid: nm for tid, nm, _ in tops}
            top_parent = {tid: p for tid, _, p in tops}
            subs = bulk_children(list(top_name), g) if top_name else []
            for _, cnm, _ in chaps:
                stree.setdefault(cnm, OrderedDict())
            for tid, tnm, cpar in tops:
                cnm = chap_name.get(cpar)
                if cnm:
                    stree[cnm].setdefault(tnm, [])
            for _, snm, tpar in subs:
                cnm = chap_name.get(top_parent.get(tpar))
                tnm = top_name.get(tpar)
                if cnm and tnm:
                    lst = stree[cnm].setdefault(tnm, [])
                    if snm not in lst:
                        lst.append(snm)
            log(f"  {s:<12} G{g}: {len(chap_name)} chapters, "
                f"{len(top_name)} topics, {len(subs)} subtopics")
    return tree


# ── Excel writing ─────────────────────────────────────────────────────────────

def load_taxonomy(csv_path=TAXONOMY_CSV, encoding=TAX_ENCODING, subjects=SUBJECT_LIST):
    """Read the Subject/Chapter/Topic/Sub-Topic CSV into an ordered nested dict
    {subject: {chapter: {topic: [subtopics]}}}. Only the requested subjects are
    kept; a requested subject with no rows simply stays absent (empty cascade).
    Returns {} if the file is missing."""
    import csv
    from collections import OrderedDict
    if not csv_path or not os.path.exists(csv_path):
        return {}

    def cn(s):
        return " ".join(str(s or "").split()).strip()

    want = {s.lower(): s for s in subjects}
    tree = OrderedDict()
    with open(csv_path, encoding=encoding) as f:
        for row in csv.DictReader(f):
            subj = want.get(cn(row.get("Subject")).lower())
            if not subj:
                continue
            ch, tp, st = (cn(row.get("Chapter Name")),
                          cn(row.get("Topic")), cn(row.get("Sub-Topic")))
            if not (ch and tp and st):
                continue
            chs = tree.setdefault(subj, OrderedDict())
            tps = chs.setdefault(ch, OrderedDict())
            sts = tps.setdefault(tp, [])
            if st not in sts:
                sts.append(st)

    _merge_bio_xlsx(tree, BIO_TOC_XLSX, want)
    return tree


def _merge_bio_xlsx(tree, xlsx_path, want):
    """Merge Botany/Zoology (and any other requested subject) from a Biology TOC
    .xlsx with columns SUBJECTNAME / CHAPTERNAME / TOPICNAME / SUBTOPICNAME into
    the in-place `tree`. `want` is {subject_lower: CanonicalName}. No-op if the
    file is missing."""
    from collections import OrderedDict
    if not xlsx_path or not os.path.exists(xlsx_path):
        return
    import openpyxl

    def cn(s):
        return " ".join(str(s or "").split()).strip()

    wb = openpyxl.load_workbook(xlsx_path, read_only=True)
    ws = wb.active
    rows = ws.iter_rows(values_only=True)
    header = [cn(h).lower() for h in next(rows)]
    idx = {name: header.index(name) for name in
           ("subjectname", "chaptername", "topicname", "subtopicname")
           if name in header}
    if len(idx) < 4:
        wb.close()
        return
    for r in rows:
        subj = want.get(cn(r[idx["subjectname"]]).lower())
        if not subj:
            continue
        ch, tp, st = (cn(r[idx["chaptername"]]), cn(r[idx["topicname"]]),
                      cn(r[idx["subtopicname"]]))
        if not (ch and tp and st):
            continue
        chs = tree.setdefault(subj, OrderedDict())
        tps = chs.setdefault(ch, OrderedDict())
        sts = tps.setdefault(tp, [])
        if st not in sts:
            sts.append(st)
    wb.close()


def write_cascade(wb, ws, col_index, tree, subjects, rows):
    """Add dependent Subject→Chapter→Topic→Subtopic dropdowns.

    A hidden 'taxonomy' sheet holds, for each level, a *key* column and a *value*
    column, laid out so every parent's children sit in a contiguous block:

        C: subject          D: chapter            (one row per chapter)
        F: "subject|chapter" G: topic             (one row per topic)
        I: "subject|chapter|topic" J: subtopic    (one row per subtopic)

    Three workbook-scoped names then return *only* the current row's children via
    OFFSET(MATCH.., COUNTIF..). The relative row reference is written as row 1 so
    that, evaluated in data row r, it reads the parent cell on the same row r.
    No per-item names and no text sanitisation, so any characters are fine.
    """
    from openpyxl.workbook.defined_name import DefinedName

    tax = wb.create_sheet("taxonomy")
    tax.sheet_state = "hidden"
    tax["A1"] = "subject"
    tax["C1"] = "chap_key";  tax["D1"] = "chapter"
    tax["F1"] = "topic_key"; tax["G1"] = "topic"
    tax["I1"] = "sub_key";   tax["J1"] = "subtopic"

    for i, s in enumerate(subjects, start=2):
        tax.cell(row=i, column=1, value=s)

    cr = fr = ir = 2   # next write-row for chapter / topic / subtopic blocks
    counts = {"chapters": 0, "topics": 0, "subtopics": 0}
    for subj in subjects:
        for ch, topics in (tree.get(subj) or {}).items():
            tax.cell(row=cr, column=3, value=subj)
            tax.cell(row=cr, column=4, value=ch); cr += 1; counts["chapters"] += 1
            for tp, subtopics in topics.items():
                tax.cell(row=fr, column=6, value=f"{subj}|{ch}")
                tax.cell(row=fr, column=7, value=tp); fr += 1; counts["topics"] += 1
                for st in subtopics:
                    tax.cell(row=ir, column=9,  value=f"{subj}|{ch}|{tp}")
                    tax.cell(row=ir, column=10, value=st); ir += 1
                    counts["subtopics"] += 1

    L = {lvl: get_column_letter(col_index[lvl])
         for lvl in ("subject", "chapter", "topic", "subtopic")}
    subj_ref = f"Tagging!${L['subject']}1"
    chap_ref = f"Tagging!${L['chapter']}1"
    top_ref  = f"Tagging!${L['topic']}1"
    t_key    = f'{subj_ref}&"|"&{chap_ref}'
    s_key    = f'{subj_ref}&"|"&{chap_ref}&"|"&{top_ref}'

    defs = {
        "ChapterList":  (f"OFFSET(taxonomy!$D$2,MATCH({subj_ref},taxonomy!$C:$C,0)-2,0,"
                         f"COUNTIF(taxonomy!$C:$C,{subj_ref}),1)"),
        "TopicList":    (f"OFFSET(taxonomy!$G$2,MATCH({t_key},taxonomy!$F:$F,0)-2,0,"
                         f"COUNTIF(taxonomy!$F:$F,{t_key}),1)"),
        "SubtopicList": (f"OFFSET(taxonomy!$J$2,MATCH({s_key},taxonomy!$I:$I,0)-2,0,"
                         f"COUNTIF(taxonomy!$I:$I,{s_key}),1)"),
    }
    for name, formula in defs.items():
        wb.defined_names[name] = DefinedName(name, attr_text=formula)

    # Subject: fixed list of the requested subjects (short β†’ safe inline).
    sub_dv = DataValidation(type="list", allow_blank=True, showDropDown=False,
                            formula1='"' + ",".join(subjects) + '"')
    ws.add_data_validation(sub_dv)
    c = get_column_letter(col_index["subject"])
    sub_dv.add(f"{c}2:{c}{rows + 1}")

    # Chapter / Topic / Subtopic: dependent lists. Errors off, so an empty parent
    # just yields an empty dropdown instead of nagging the user.
    for col, name in (("chapter", "ChapterList"), ("topic", "TopicList"),
                      ("subtopic", "SubtopicList")):
        dv = DataValidation(type="list", formula1=name, allow_blank=True,
                            showDropDown=False, showErrorMessage=False)
        dv.prompt = f"Pick a {col} (depends on the level above)"
        dv.promptTitle = col
        ws.add_data_validation(dv)
        cl = get_column_letter(col_index[col])
        dv.add(f"{cl}2:{cl}{rows + 1}")

    return counts


def build_workbook(options, out_path, rows=1000, taxonomy=None, subjects=None,
                   sample_rows=None):
    """Write the template with header columns + data-validation dropdowns.

    Flat-list option values live on a hidden '_lists' sheet (one column each) and
    the validations reference those ranges β€” this avoids Excel's 255-char inline
    limit and survives commas inside option text.

    When taxonomy data is available, Subject/Chapter/Topic/Subtopic become
    dependent (cascading) dropdowns instead (see write_cascade).
    """
    if subjects is None:
        subjects = SUBJECT_LIST
    if taxonomy is None:
        taxonomy = load_taxonomy(subjects=subjects)
    cascade_active = bool(taxonomy)

    wb = Workbook()
    ws = wb.active
    ws.title = "Tagging"
    ws.append(COLUMN_ORDER)

    for row in (sample_rows or []):
        ws.append([row.get(col, "") for col in COLUMN_ORDER])

    lists = wb.create_sheet("_lists")
    lists.sheet_state = "hidden"

    col_index = {name: i + 1 for i, name in enumerate(COLUMN_ORDER)}

    # Subject is handled by the cascade when taxonomy is present; don't also give
    # it a flat scraped-list dropdown (that would be a duplicate validation).
    cascade_cols = {"subject", "chapter", "topic", "subtopic"} if cascade_active else set()

    lcol = 0
    for field in SCRAPE_FIELDS:
        col = field["col"]
        if col in cascade_cols:
            continue
        values = options.get(col) or field.get("default", [])
        # Skip when there's nothing to offer, or the list is too big for a picker.
        if not values or len(values) > MAX_DROPDOWN_OPTIONS:
            continue
        lcol += 1
        lcol_letter = get_column_letter(lcol)
        lists.cell(row=1, column=lcol, value=col)              # header for clarity
        for r, val in enumerate(values, start=2):
            lists.cell(row=r, column=lcol, value=val)
        ref = f"_lists!${lcol_letter}$2:${lcol_letter}${len(values) + 1}"

        dv = DataValidation(type="list", formula1=ref, allow_blank=True,
                            showDropDown=False)
        dv.error = f"Pick a value from the {col} list."
        dv.errorTitle = "Invalid value"
        dv.prompt = f"Choose a {col}"
        dv.promptTitle = col
        ws.add_data_validation(dv)

        col_letter = get_column_letter(col_index[col])
        dv.add(f"{col_letter}2:{col_letter}{rows + 1}")

    if cascade_active:
        write_cascade(wb, ws, col_index, taxonomy, subjects, rows)

    # widen the header columns a touch for readability
    for name, idx in col_index.items():
        ws.column_dimensions[get_column_letter(idx)].width = max(12, min(len(name) + 4, 26))

    wb.save(out_path)


# ── CLI ───────────────────────────────────────────────────────────────────────

def main():
    ap = argparse.ArgumentParser(description="Generate the CMS tagging Excel template "
                                             "with live-scraped dropdowns + data validation.")
    ap.add_argument("--state", help="Playwright storage_state JSON (default: newest saved session)")
    ap.add_argument("--qid", help="Existing question id to open via Edit Details (most reliable)")
    ap.add_argument("--out", default=os.path.join(DATA_DIR, "tagging_template.xlsx"),
                    help="Output .xlsx path (default: tagging_template.xlsx)")
    ap.add_argument("--no-scrape", action="store_true",
                    help="Skip CMS; build the template from built-in default lists")
    ap.add_argument("--from-lookups", action="store_true",
                    help="Fill Other-Details dropdowns from the QB /lookups API "
                         "(no browser) instead of scraping the form with Playwright")
    ap.add_argument("--headed", dest="headless", action="store_false",
                    help="Show the browser window (default)")
    ap.add_argument("--headless", dest="headless", action="store_true",
                    help="Run the browser headless")
    ap.add_argument("--toc", default=TAXONOMY_CSV,
                    help="Subject/Chapter/Topic/Sub-Topic CSV for the cascading dropdowns")
    ap.add_argument("--no-cascade", action="store_true",
                    help="Skip the dependent Subject→Chapter→Topic→Subtopic dropdowns")
    ap.add_argument("--from-cms", action="store_true",
                    help="Build the Subject→Chapter→Topic→Subtopic cascade LIVE from "
                         "the CMS community API instead of the offline CSV/xlsx")
    ap.add_argument("--examples", action="store_true",
                    help="Include illustrative example rows (for the sample workbook)")
    ap.set_defaults(headless=False)
    args = ap.parse_args()

    options = {}
    if args.no_scrape:
        print("Skipping scrape β€” using built-in default lists.")
    elif args.from_lookups:
        state_file = pick_state_file(args.state)
        if not state_file:
            sys.exit("--from-lookups needs a saved CMS session (none found). "
                     "Connect on /tagger first, or pass --state.")
        print(f"Fetching Other-Details options from /lookups using: {state_file}")
        try:
            options = lookups_options(state_file)
            for col, vals in options.items():
                print(f"  lookups {col:<14} {len(vals)} option(s)")
        except Exception as e:
            print(f"/lookups fetch failed ({e}). Falling back to built-in default lists.")
    else:
        state_file = pick_state_file(args.state)
        if not state_file:
            print("No saved CMS session found β€” falling back to built-in default lists.\n"
                  "  (Set up the CMS login first, or pass --state, to scrape live options.)")
        else:
            print(f"Using CMS session: {state_file}")
            try:
                options = scrape_options(state_file, args.qid, args.headless)
            except Exception as e:
                print(f"Scrape failed ({e}). Falling back to built-in default lists.")

    # Report what each scrape-able column will use for its dropdown.
    print("\nColumn dropdown sources:")
    validated = []
    for f in SCRAPE_FIELDS:
        col = f["col"]
        if options.get(col):
            print(f"  {col:<14} {len(options[col])} scraped option(s)")
            validated.append(col)
        elif f.get("default"):
            print(f"  {col:<14} default list ({len(f['default'])})")
            validated.append(col)
        else:
            print(f"  {col:<14} no options found β€” left as free text")

    if args.no_cascade:
        taxonomy = {}
    elif args.from_cms:
        print("\nBuilding Subject -> Chapter -> Topic -> Subtopic cascade LIVE from CMS "
              "(community API)...")
        try:
            taxonomy = cms_taxonomy()
        except Exception as e:
            print(f"CMS taxonomy build failed ({e}). Falling back to offline CSV/xlsx.")
            taxonomy = load_taxonomy(args.toc)
    else:
        taxonomy = load_taxonomy(args.toc)
    if not args.no_cascade:
        if taxonomy:
            print("\nCascading taxonomy (Subject -> Chapter -> Topic -> Subtopic):")
            for s in SUBJECT_LIST:
                t = taxonomy.get(s)
                if t:
                    nt = sum(len(v) for v in t.values())
                    nst = sum(len(st) for v in t.values() for st in v.values())
                    print(f"  {s:<12} {len(t)} chapters, {nt} topics, {nst} subtopics")
                else:
                    print(f"  {s:<12} (no offline data β€” cascade empty; scrape from CMS later)")
        else:
            print(f"\nNo taxonomy CSV at {args.toc} β€” Subject/Chapter/Topic/Subtopic "
                  "will be plain columns.")

    # Pass taxonomy through so build_workbook doesn't re-read the CSV.
    build_workbook(options, args.out, taxonomy=(taxonomy or None),
                   sample_rows=(EXAMPLE_ROWS if args.examples else None))
    cascade_on = bool(taxonomy)
    free_cols = [f["col"] for f in FIELDS if f["mode"] == "free"
                 and not (cascade_on and f["col"] in ("chapter", "topic", "subtopic"))]
    print(f"\nTemplate written: {args.out}")
    print("Columns:", ", ".join(COLUMN_ORDER))
    if cascade_on:
        print("Cascading dropdowns: subject -> chapter -> topic -> subtopic")
        validated = [c for c in validated if c != "subject"]
    print("Flat dropdowns:", ", ".join(validated))
    print("Free text:", ", ".join(free_cols))


if __name__ == "__main__":
    main()