File size: 26,782 Bytes
31ee18f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Parse Appell "Cosmetics, Fragrances and Flavors" perfume formulary.

Two phases:
1. Extract the code tables (pages 280-291) to map abbreviations to full names.
2. Extract formulas from the French-style (293-307), floral (308-329), and soap/cosmetic
   (330-343) sections.

Formulas total 1000 parts. We resolve codes to full names and then to CAS via
TradeNameResolver. Formulas that are partially resolvable are kept; unresolved
components are flagged as sub_base/unknown.
"""
from __future__ import annotations

import argparse
import json
import re
from pathlib import Path
from typing import Any

import sys

sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

from pino.trade_name_resolver import TradeNameResolver


# ---------------------------------------------------------------------------
# Code tables (pages 280-291). We hardcode the tables here because parsing the
# multi-column PDF text reliably is brittle; the tables are small and stable.
# ---------------------------------------------------------------------------

AROMATIC_CHEMICAL_CODES: dict[str, str] = {
    "Ac Ph": "Acetophenone",
    "Ald C7": "Aldehyde C 7",
    "Ald C 7": "Aldehyde C 7",
    "Ald C8": "Aldehyde C 8",
    "Ald C 8": "Aldehyde C 8",
    "Ald C9": "Aldehyde C 9",
    "Ald C 9": "Aldehyde C 9",
    "Ald C10": "Aldehyde C 10",
    "Ald C 10": "Aldehyde C 10",
    "Ald C11": "Aldehyde C 11 undecylenic",
    "Ald C 11": "Aldehyde C 11 undecylenic",
    "MNA": "Methyl nonyl acetaldehyde",
    "UnLac": "Undecalactone",
    "EMPG": "Ethyl methyl phenyl glycidate",
    "NoLac": "Nonalactone",
    "Am Ac": "i-Amyl acetate",
    "Am Bz": "i-Amyl benzoate",
    "Am Bu": "i-Amyl butyrate",
    "Am Cin Ald": "Amyl cinnamic aldehyde",
    "Am PhAc": "i-Amyl phenylacetate",
    "Am Sal": "i-Amyl salicylate",
    "An": "Anethole",
    "An Ald": "Anisic aldehyde",
    "An Ac": "Anisyl acetate",
    "Bz Ald": "Benzaldehyde",
    "BzPh": "Benzophenone",
    "Bz Ac": "Benzyl acetate",
    "Bz Alc": "Benzyl alcohol",
    "Bz Bz": "Benzyl benzoate",
    "Bz Cin": "Benzyl cinnamate",
    "Bz For": "Benzyl formate",
    "Bz PhAc": "Benzyl phenylacetate",
    "Bz Pr": "Benzyl propionate",
    "Bz Sal": "Benzyl salicylate",
    "BZA": "Benzylidene acetone",
    "Br": "Bromostyrole",
    "Bu Bz": "i-Butyl benzoate",
    "BH Ac": "p-t-Butyl cyclohexyl acetate",
    "Cp": "Camphor crystals",
    "Cc": "Carvacrol",
    "Cv": "1-Carvone",
    "Cd": "Cedrol",
    "Cd Ac": "Cedryl acetate",
    "Cin Alc": "Cinnamic alcohol",
    "Cin Ald": "Cinnamic aldehyde",
    "Cin Ac": "Cinnamyl acetate",
    "Ci": "Citral",
    "Ct": "Citronellal",
    "Cl": "Citronellol",
    "Cl Ac": "Citronellyl acetate",
    "COA": "Citronellyl oxy-acetaldehyde",
    "Co": "Coumarin",
    "Cr Ac": "p-Cresyl acetate",
    "PCME": "p-Cresyl methyl ether",
    "Cr PhAc": "p-Cresyl phenylacetate",
    "Cum Ald": "Cuminic aldehyde",
    "Cy": "Cyclamen aldehyde",
    "DEP": "Diethyl phthalate",
    "DM Ant": "Dimethyl anthranilate",
    "DMBC Ac": "Dimethyl benzyl carbinol acetate",
    "DMH": "Dimethyl hydroquinone",
    "Dp": "Dipentine",
    "DPO": "Diphenyl oxide",
    "DPG": "Dipropylene glycol",
    "Et Am K": "Ethyl i-amyl ketone",
    "Et Bz": "Ethyl benzoate",
    "Et Bu": "Ethyl i-butyrate",
    "Et Cin": "Ethyl cinnamate",
    "Et Oen": "Ethyl oenanthate",
    "Et Pel": "Ethyl pelargonate",
    "Et PhAc": "Ethyl phenylacetate",
    "Et Pr": "Ethyl propionate",
    "Et Sal": "Ethyl salicylate",
    "Et Val": "Ethyl i-valerate",
    "Et Va": "Ethyl vanillin",
    "Eu": "Eugenol",
    "Eu Ac": "Eugenol acetate",
    "Gu Ac": "Guayol acetate",
    "Gl": "Geraniol",
    "Gl Ac": "Geranyl acetate",
    "Gl For": "Geranyl formate",
    "Gl Bu": "Geranyl i-butyrate",
    "2Hx Ald": "2-Hexenal",
    "2Hx Alc": "2-Hexenol",
    "Hx Cin Ald": "Hexyl cinnamic aldehyde",
    "He": "Heliotropin",
    "HTA": "Hydratropic aldehyde",
    "HTA-DMA": "Hydratropic aldehyde dimethyl acetal",
    "Hy": "Hydroxycitronellal",
    "Et AAc": "Ethyl acetoacetate",
    "In": "Indole",
    "Io": "Ionone alpha",
    "i-Bo Ac": "Isobornyl acetate",
    "i-Bo For": "Isobornyl formate",
    "i-Bo Pr": "Isobornyl propionate",
    "ic-Ci": "Isocyclocitral",
    "i-Eu": "Isoeugenol",
    "i-Eu Ac": "Isoeugenol acetate",
    "i-Ja": "Isojasmone",
    "Lil": "Lilial",
    "Lm": "Limonene",
    "Lin": "Linalool",
    "Lin Ac": "Linalyl acetate",
    "Lin Pr": "Linalyl propionate",
    "MI": "Menthol",
    "Mn": "Menthone",
    "Me AcPh": "p-Methyl acetophenone",
    "Me Ant": "Methyl anthranilate",
    "Me Bz": "Methyl benzoate",
    "Me Cin": "Methyl cinnamate",
    "Me Eu": "Methyl eugenol",
    "Me i-Eu": "Methyl isoeugenol",
    "MHC": "Methyl heptine carbonate",
    "Me In": "Methyl indole",
    "MNK": "Methyl naphthyl ketone",
    "Me HTA": "p-Methyl hydratropic aldehyde",
    "Me Io": "Methyl ionone",
    "MNA": "Methyl nonyl acetaldehyde",
    "Me PhAc": "Methyl phenylacetate",
    "Me Q": "p-Methyl quinoline",
    "Me Sal": "Methyl salicylate",
    "Me Un": "Methyl undecylenate",
    "MA": "Musk ambrette",
    "MK": "Musk ketone",
    "MX": "Musk xylene",
    "MB": "Musc brassylate",
    "M P": "Musc pentadecanolide",
    "NI": "Nerol",
    "Ne": "Nerolin",
    "NoLac": "Nonalactone",
    "Nol Ac": "1,3-Nonanediol acetate",
    "No Ac": "Nonyl acetate",
    "Oc Ac": "Octyl acetate",
    "PhA": "Phenylacetaldehyde",
    "PhA-DMA": "Phenylacetaldehyde dimethylacetal",
    "PhAc Acid": "Phenylacetic acid",
    "PhEt Ac": "Phenylethyl acetate",
    "PhEt Alc": "Phenylethyl alcohol",
    "PhEt For": "Phenylethyl formate",
    "PhEt Pr": "Phenylethyl propionate",
    "PhPr Ac": "Phenylpropyl acetate",
    "PhPr Alc": "Phenylpropyl alcohol",
    "PhPr Ald": "Phenylpropyl aldehyde",
    "PG": "Propylene glycol",
    "Rasp cryst": "Raspberry crystals",
    "Rose cryst": "Rose crystals",
    "Rose Oxide": "Rose oxide",
    "Rl": "Rhodinol",
    "Sa": "Safrole",
    "Sal Ald": "Salicylic aldehyde",
    "Se": "Sedanolid",
    "Skatol": "Methyl indole",
    "St Ac": "Styrallyl acetate",
    "Tl": "Terpineol",
    "Tl Ac": "Terpinyl acetate",
    "THG": "Tetrahydrogeraniol",
    "THMQ": "Tetrahydro p-methyl quinoline",
    "Thu": "Thujone",
    "Th": "Thymol",
    "UnLac": "Undecalactone",
    "Va": "Vanillin",
    "Vi": "Vetiverol",
    "Vl Ac": "Vetiveryl acetate",
    "Ya": "Yara-yara",
    "Lav abs": "Lavender absolute",
    "Org tpl": "Orange terpeneless",
    "Brg tpl": "Bergamot terpeneless",
    "Ori crt": "Orris concrete",
    "Ben res": "Benzoin resinoid",
    "Lab res": "Labdanum resinoid",
    "Sty res": "Styrax resinoid",
    "Gal res": "Galbanum resinoid",
    "Ton res": "Tonka resinoid",
    "Myr res": "Myrrh resinoid",
    "Opo res": "Opoponax resinoid",
    "Civ res": "Civet resinoid",
    "Civ abs": "Civet absolute",
    "Civ Tr": "Civet tincture",
    "Msk Tr": "Musk tincture",
    "Van Tr": "Vanilla tincture",
    "Cas Tr": "Cassie tincture",
    "Ambrene 50": "Ambrene 50%",
    "Ambrarome 5": "Ambrarome 5%",
    "Ambrarome 10": "Ambrarome 10%",
    "Ambrarome 50": "Ambrarome 50%",
    "Base Poivre 10": "Base Poivre 10%",
    "Dianthus 10": "Dianthus 10%",
    "Lilac 50": "Lilac 50%",
    "Jasmin 50": "Jasmin 50%",
    "Jasmin 30": "Jasmin 30%",
    "Jasmin 70": "Jasmin 70%",
    "Jasmin Fl 100": "Jasmin Flower 100%",
    "Jasmin Flower 100": "Jasmin Flower 100%",
    "Rose W": "Rose W",
    "Acacia 10": "Acacia 10%",
    "Narcissus 30": "Narcissus 30%",
    "Hyacinth 10": "Hyacinth 10%",
    "Muguet 10A": "Muguet 10A",
    "Muguet 10 B": "Muguet 10 B",
    "Tuberose 10": "Tuberose 10%",
    "Carnation 10": "Carnation 10%",
    "UnLac 10": "Undecalactone 10%",
    "Cos 10": "Costus 10%",
    "MdC 10": "Mousse de Chene Integrale 10%",
    "Ori crt 10": "Orris concrete 10%",
    "Ben res 10": "Benzoin resinoid 10%",
    "Ben res 50": "Benzoin resinoid 50%",
    "Lab abs 10": "Labdanum absolute 10%",
    "Lab abs 50": "Labdanum absolute 50%",
    "Sty res 10": "Styrax resinoid 10%",
    "Org tpl 10": "Orange terpeneless 10%",
    "Civ Tr 10": "Civet tincture 10%",
    "Civ Tr 3": "Civet tincture 3%",
    "Msk Tr 3": "Musk tincture 3%",
    "Van Tr 10": "Vanilla tincture 10%",
    "Ald C 9,10%": "Aldehyde C 9 10%",
    "Ald C 10,10%": "Aldehyde C 10 10%",
    "Ald C 11,10%": "Aldehyde C 11 10%",
    "Ald C 12,10%": "Aldehyde C 12 10%",
    "Ald C 10,1%": "Aldehyde C 10 1%",
    "Ald C 11,1%": "Aldehyde C 11 1%",
    "MNA 1%": "Methyl nonyl acetaldehyde 1%",
    "MNA 10%": "Methyl nonyl acetaldehyde 10%",
    "Al Io 10%": "Allyl ionone 10%",
    "Al Cap 1%": "Allyl caproate 1%",
    "Al Cap 10%": "Allyl caproate 10%",
    "i-Bu Q 10%": "i-Butyl quinoline 10%",
    "i-Bu Sal": "i-Butyl salicylate",
    "Et Est 10%": "Ethyl ester 10%",
    "Est 10%": "Estragon 10%",
    "S-CinG": "Spicy cinnamon group",
    "2Hx Ald 0.1%": "2-Hexenal 0.1%",
    "In 10%": "Indole 10%",
    "p-Cr Ac": "p-Cresyl acetate",
    "p-Cresol 10%": "p-Cresol 10%",
    "PhA 10%": "Phenylacetaldehyde 10%",
    "PhA 50%": "Phenylacetaldehyde 50%",
    "PhPr Ald 10%": "Phenylpropyl aldehyde 10%",
    "PhPr Alc 10%": "Phenylpropyl alcohol 10%",
    "BH Ac10%": "p-t-Butyl cyclohexyl acetate 10%",
    "DMBC Ac": "Dimethyl benzyl carbinol acetate",
    "DH Ja1%": "Dihydroisojasmone 1%",
    "DH Jai%": "Dihydroisojasmone 1%",
}

ESSENTIAL_OIL_CODES: dict[str, str] = {
    "Amb": "Ambrette seed",
    "Amg": "Ambergris",
    "Amy": "Amyris",
    "Ang": "Angelica seed",
    "Ani": "Anise oil",
    "Arm": "Armoise oil",
    "Asp": "Lavender spike oil",
    "Bas": "Basil oil",
    "Bay": "Bay oil",
    "Ben": "Benzoin resinoid",
    "Brg": "Bergamot oil",
    "BdR": "Bois de rose oil",
    "Cad": "Cade oil",
    "Cal": "Calamus oil",
    "Cpr": "Camphor oil",
    "Can": "Cananga oil",
    "Cay": "Caraway oil",
    "Com": "Cardamom oil",
    "Cot": "Carrot seed oil",
    "Csc": "Cascarilla oil",
    "Cia": "Cassia oil",
    "Cie": "Cassie absolute",
    "Cas": "Castoreum",
    "Cdl": "Cedarleaf oil",
    "Cdw": "Cedarwood oil",
    "Cel": "Celery seed oil",
    "Cam": "Chamomile oil",
    "Cin C": "Cinnamon Ceylon oil",
    "Cil": "Cinnamon leaf oil",
    "Cis": "Cistus labdanum",
    "Cta C": "Citronella Ceylon oil",
    "Cta J": "Citronella Java oil",
    "Civ": "Civet",
    "Clo": "Clove oil",
    "Cor": "Coriander oil",
    "Cos": "Costus oil",
    "Cub": "Cubeb oil",
    "Cum": "Cumin oil",
    "Dil": "Dillweed oil",
    "Ele": "Elemi oil",
    "Est": "Estragon oil",
    "Euc": "Eucalyptus oil",
    "FdO": "Fleur d'Oranger",
    "Fen": "Fennel seed oil",
    "Fir": "Fir needle Siberian oil",
    "Gal": "Galbanum oil",
    "Gal res": "Galbanum resinoid",
    "Ger": "Geranium oil",
    "Gin": "Ginger oil",
    "Gua": "Guaiacwood oil",
    "Hem": "Hemlock spruce oil",
    "Hya": "Hyacinth absolute",
    "Hys": "Hyssop oil",
    "Imo": "Immortelle absolute",
    "Ori": "Orris",
    "Jas": "Jasmin absolute",
    "Jas abs": "Jasmin absolute",
    "Jon": "Jonquil absolute",
    "Jun": "Juniper berry oil",
    "Lab": "Labdanum",
    "Lab abs": "Labdanum absolute",
    "Lab res": "Labdanum resinoid",
    "Lvn": "Lavandin oil",
    "Lav": "Lavender oil",
    "Lav abs": "Lavender absolute",
    "Lem": "Lemon oil",
    "Lmg": "Lemongrass oil",
    "Lim": "Lime distilled oil",
    "Lrl": "Laurel leaf oil",
    "Lvg": "Lovage oil",
    "Man": "Mandarin oil",
    "Mrg": "Marjoram wild oil",
    "Mim": "Mimosa absolute",
    "Mdc": "Mousse de Chene",
    "Mou": "Mousse de Chene",
    "Musk": "Musk natural",
    "Myr": "Myrrh oil",
    "Myr res": "Myrrh resinoid",
    "Ner": "Neroli oil",
    "Nut": "Nutmeg oil",
    "Oak": "Oak moss",
    "Oga": "Origanum oil",
    "Oli": "Olibanum oil",
    "Oli res": "Olibanum resinoid",
    "OpO": "Opoponax oil",
    "Opo": "Opoponax oil",
    "Opo res": "Opoponax resinoid",
    "Pal": "Palmarosa oil",
    "Pars": "Parsley oil",
    "Pat": "Patchouli oil",
    "Ppr": "Pepper black oil",
    "Pen": "Pennyroyal oil",
    "Mnt": "Peppermint oil",
    "Peru": "Peru balsam oil",
    "Ptg": "Petitgrain oil",
    "Pim": "Pimenta berries oil",
    "Res": "Reseda absolute",
    "Ros": "Rose absolute",
    "Ros abs": "Rose absolute",
    "Ros B": "Rose Bulgarian otto",
    "Rsm": "Rosemary oil",
    "SgC": "Sage Clary oil",
    "SgD": "Sage Dalmatian oil",
    "Sgs": "Sage Spanish oil",
    "San": "Sandalwood oil",
    "Sas": "Sassafras oil",
    "Spm": "Spearmint oil",
    "Spr": "Spruce oil",
    "Sty": "Styrax oil",
    "Tan": "Tansy oil",
    "Ton": "Tonka",
    "Tar": "Tarragon oil",
    "Thy": "Thyme white oil",
    "Tolu": "Tolu balsam",
    "Tub": "Tuberose absolute",
    "Van": "Vanilla",
    "Verb": "Verbena oil",
    "Vet": "Vetiver oil",
    "Vl": "Vetiverol",
    "Vio": "Violet leaves absolute",
    "Yig": "Ylang-ylang oil",
    "Ylg": "Ylang-ylang oil",
    "Org": "Orange sweet oil",
}

ABBREVIATION_EXPANSIONS: dict[str, str] = {
    "abs": "absolute",
    "res": "resinoid",
    "crt": "concrete",
    "Tr": "tincture",
    "Fl": "flower",
    "tpl": "terpeneless",
    "sub": "substitute",
    "tls": "terpeneless",
    "tps": "terpenes",
    "distillate": "distillate",
    "(d)": "decolorized",
    "SB": "Schiff base",
}


def build_code_map() -> dict[str, str]:
    """Merge all Appell code tables into one lookup."""
    code_map = {}
    code_map.update(AROMATIC_CHEMICAL_CODES)
    code_map.update(ESSENTIAL_OIL_CODES)
    code_map.update(ABBREVIATION_EXPANSIONS)
    # Alias lower-case keys
    for k, v in list(code_map.items()):
        code_map.setdefault(k.lower(), v)
    return code_map


CODE_MAP = build_code_map()

# Header patterns
FRENCH_HEADER_RE = re.compile(r'Type\s+["“]([^"”]+)["”](?:\s*\(([^)]+)\))?')

# Floral fragrances section headers: Name + number (10, 20, 30, 40, 50, 70, 100, etc.)
# Only match in the floral section to avoid matching sub-base references like "Jasmin 50".
FLORAL_HEADER_RE = re.compile(
    r'^(Jasmin|Rose|Lilac|Jasmin Flower|Jonquil|Narcissus|Acacia|Dianthus|Hyacinth|'
    r'Muguet|Tuberose|Carnation|Lily|Violet|Freesia|Gardenia|Orange Blossom|Magnolia|Iris|Sweet Pea|Wall Flower|Wisteria|Jacinthe|Honeysuckle)\s+'
    r'(\d+(?:\s*[A-C])?)$',
    re.IGNORECASE,
)

SOAP_HEADER_RE = re.compile(
    r'^(Cologne|Floral Bouquet|Foug[eè]re|Geranium|Soap Perfume|Rose|Lavender|'
    r'Sandalwood|Chypre|Muguet|Jasmin|Oriental|Fruit|Amber|Aldehydic|Citrus|Spicy|Fresh|'
    r'Transparent|Green|Powdery|Woody|Floral|Musk|Sweet|Balsamic|Coniferous|Herbal|Leather|Tobacco|'
    r'Apple|May Blossom|Neroli|Verbena|Ylang)\s+S\s*(\d+)$',
    re.IGNORECASE,
)

SECTION_RE = re.compile(r'^(9-1\.\s+Perfumes \(French Style\)|9-2\.\s+Cologne fragrances|9-3\.\s+Floral fragrances|9-4\.\s+Perfumes for cosmetics and soap|Floral fragrances|Perfumes, French style|Perfumes for cosmetics and soaps|Perfume formulations|9\.\s+Perfume formulations)', re.IGNORECASE)


# ---------------------------------------------------------------------------
# Formula extraction
# ---------------------------------------------------------------------------

def _expand_code(raw_code: str) -> str | None:
    """Expand an Appell code to a full name. Handles compound codes and suffixes."""
    raw = raw_code.strip()
    if not raw:
        return None

    # Direct lookup (case-insensitive)
    if raw in CODE_MAP:
        return CODE_MAP[raw]
    lower = raw.lower()
    if lower in CODE_MAP:
        return CODE_MAP[lower]

    # Strip percentage suffixes like "10%", "50%", "3%", "1%", "0.1%"
    pct_match = re.search(r'\s*(\d+(?:\.\d+)?)\s*%\s*$', raw)
    base = re.sub(r'\s*\d+(?:\.\d+)?\s*%\s*$', '', raw).strip() if pct_match else raw
    pct = f" {pct_match.group(1)}%" if pct_match else ""

    if base in CODE_MAP:
        return CODE_MAP[base] + pct
    if base.lower() in CODE_MAP:
        return CODE_MAP[base.lower()] + pct

    # Handle compound codes: e.g., "Me Io" -> "Methyl ionone", "Cl Ac" -> "Citronellyl acetate"
    # Split into tokens and try to expand token by token
    tokens = base.split()
    if len(tokens) >= 2:
        # Try as a whole first via underscore join
        joined = " ".join(tokens)
        if joined in CODE_MAP:
            return CODE_MAP[joined] + pct
        # Expand radical + functional: e.g., "Me" + "Bz" = "Methyl benzoate"
        # This is ambiguous, so prefer exact matches from the table above.

    # Try stripping suffixes like abs, res, Tr, tpl, Fl and looking up base
    for suffix, expansion in ABBREVIATION_EXPANSIONS.items():
        if base.lower().endswith(suffix.lower()):
            prefix = base[: -len(suffix)].strip()
            if prefix in CODE_MAP:
                return CODE_MAP[prefix] + " " + expansion + pct
            if prefix.lower() in CODE_MAP:
                return CODE_MAP[prefix.lower()] + " " + expansion + pct

    # Try adding common suffixes if the raw code itself is not found but is a known base
    # e.g., "Jas" not found, but "Jas abs" is; we already handled suffix stripping above.

    return None


def _extract_amount(line: str) -> tuple[float | None, str]:
    """Try to extract a leading or trailing amount from a line."""
    # Leading amount: "30 Brg"
    m = re.match(r'^(\d+(?:\.\d+)?)\s+(.+)$', line.strip())
    if m:
        return float(m.group(1)), m.group(2).strip()
    # Trailing amount: "Bz Ac 50"
    m = re.match(r'^(.+?)\s+(\d+(?:\.\d+)?)\s*$', line.strip())
    if m:
        return float(m.group(2)), m.group(1).strip()
    return None, line.strip()


def _line_to_components(line: str) -> list[dict[str, Any]] | None:
    """Convert a formula line into one or more components."""
    line = line.strip()
    if not line or len(line) < 3:
        return None

    # Skip totals and page numbers
    if re.match(r'^\d{1,4}$', line):
        return None
    if re.match(r'^T\s+1000', line, re.IGNORECASE):
        return None
    if "continued" in line.lower() or "Perfumes, French style" in line or "Floral fragrances" in line or "Perfumes for cosmetics and soaps" in line:
        return None

    amount, remainder = _extract_amount(line)
    if amount is None:
        return None

    # Sometimes a line has multiple codes and one amount at the end: "A B C 100"
    # Split the remainder and try to assign the amount to each recognized code.
    tokens = remainder.split()

    # Heuristic: if the last token is a percentage, it applies to the whole line
    pct = ""
    if tokens and re.match(r'\d+(?:\.\d+)?%', tokens[-1]):
        pct = tokens.pop()

    # Try to find the longest code prefix in the remaining tokens
    components = []
    i = 0
    while i < len(tokens):
        # Try matching 1, 2, or 3 token codes
        found = False
        for n in range(min(3, len(tokens) - i), 0, -1):
            candidate = " ".join(tokens[i : i + n])
            expanded = _expand_code(candidate + (" " + pct if pct else ""))
            if expanded is None and pct:
                expanded = _expand_code(candidate)
            if expanded:
                components.append({"name": expanded, "amount": amount, "raw_code": candidate + (" " + pct if pct else "")})
                i += n
                found = True
                break
        if not found:
            # Unrecognized token, skip it
            i += 1

    # If we recognized nothing, keep the raw line as unknown with amount
    if not components and remainder:
        components.append({"name": remainder + (" " + pct if pct else ""), "amount": amount, "raw_code": remainder + (" " + pct if pct else "")})

    return components


def _detect_headers(text: str) -> list[tuple[int, str, str | None]]:
    """Return list of (line_index, header_name, extra_info) for formula headers."""
    headers = []
    current_section: str | None = None
    lines = text.splitlines()
    for i, line in enumerate(lines):
        line = line.strip()
        if not line:
            continue

        section_m = SECTION_RE.match(line)
        if section_m:
            current_section = section_m.group(1)
            continue

        m = FRENCH_HEADER_RE.match(line)
        if m and (current_section is None or "french" in current_section.lower()):
            headers.append((i, m.group(1).strip(), m.group(2)))
            continue

        m = FLORAL_HEADER_RE.match(line)
        if m and current_section and "floral" in current_section.lower():
            headers.append((i, f"{m.group(1)} {m.group(2)}", None))
            continue

        m = SOAP_HEADER_RE.match(line)
        if m and current_section and ("soap" in current_section.lower() or "cosmetic" in current_section.lower()):
            headers.append((i, f"{m.group(1)} S {m.group(2)}", None))

    return headers


def _is_header_line(line: str, current_section: str | None = None) -> bool:
    line = line.strip()
    if FRENCH_HEADER_RE.match(line):
        return current_section is None or "french" in current_section.lower()
    if FLORAL_HEADER_RE.match(line):
        return current_section is not None and "floral" in current_section.lower()
    if SOAP_HEADER_RE.match(line):
        return current_section is not None and ("soap" in current_section.lower() or "cosmetic" in current_section.lower())
    return False


def parse_appell_pages(records: list[dict[str, Any]], page_range: tuple[int, int] | None = None) -> list[dict[str, Any]]:
    """Parse Appell pages into formula entries."""
    formulas = []
    current_section: str | None = None
    for record in records:
        source = record.get("source", "")
        if not source.startswith("Cosmetics"):
            continue
        page = record.get("page", 0)
        if page_range and not (page_range[0] <= page <= page_range[1]):
            continue
        text = record.get("text", "")
        # Update section from this page before parsing headers
        for line in text.splitlines():
            s = SECTION_RE.match(line.strip())
            if s:
                current_section = s.group(1)
        headers = _detect_headers(text)
        lines = text.splitlines()

        for idx, (line_idx, header, extra) in enumerate(headers):
            header_section = current_section
            if header_section is None:
                for ln in range(0, line_idx):
                    s = SECTION_RE.match(lines[ln].strip())
                    if s:
                        header_section = s.group(1)
            end_idx = headers[idx + 1][0] if idx + 1 < len(headers) else len(lines)
            components = []
            for ln in range(line_idx + 1, end_idx):
                raw_line = lines[ln].strip()
                if not raw_line or _is_header_line(raw_line, header_section):
                    continue
                comps = _line_to_components(raw_line)
                if comps:
                    components.extend(comps)

            total = sum(c["amount"] for c in components)
            # Appell formulas total 1000 parts; reject obvious fragments
            if total < 500 or total > 1500:
                continue
            if len(components) < 3:
                continue

            formulas.append({
                "formula_id": f"appell_p{page:04d}_{len(formulas):04d}",
                "name": header,
                "source": source,
                "page": page,
                "extra": extra,
                "components": components,
                "raw_basis_sum": total,
            })

    return formulas


def resolve_appell_formulas(raw_formulas: list[dict[str, Any]], resolver: TradeNameResolver | None = None) -> list[dict[str, Any]]:
    """Resolve Appell formula components to CAS using TradeNameResolver."""
    if resolver is None:
        resolver = TradeNameResolver()

    resolved_formulas = []
    for raw in raw_formulas:
        components = []
        for c in raw["components"]:
            name = c["name"]
            cas = resolver.resolve(name)
            if cas:
                components.append({"cas": cas, "amount": c["amount"], "type": "pure", "raw_name": name})
            else:
                components.append({"name": name, "amount": c["amount"], "type": "unknown", "raw_code": c.get("raw_code", name)})

        if all(c["type"] == "unknown" for c in components):
            continue

        total = sum(c["amount"] for c in components)
        if total <= 0:
            continue

        normalized = []
        for c in components:
            entry = {"amount": round(c["amount"] / total, 6)}
            if c["type"] == "unknown":
                entry["type"] = "sub_base"
                entry["name"] = c["name"]
            else:
                entry["type"] = "pure"
                entry["cas"] = c["cas"]
            normalized.append(entry)

        resolved_formulas.append({
            "formula_id": raw["formula_id"],
            "name": raw["name"],
            "source": raw["source"],
            "page": raw["page"],
            "extra": raw.get("extra"),
            "raw_basis_sum": total,
            "components": normalized,
        })

    return resolved_formulas


def main() -> int:
    parser = argparse.ArgumentParser(description="Parse Appell perfume formulary")
    parser.add_argument("--input", required=True, help="Input literature_pages.jsonl")
    parser.add_argument("--output", required=True, help="Output JSONL of resolved formulas")
    parser.add_argument("--raw-output", help="Optional raw parsed formulas JSONL")
    parser.add_argument("--start-page", type=int, default=293, help="First Appell formula page")
    parser.add_argument("--end-page", type=int, default=343, help="Last Appell formula page")
    args = parser.parse_args()

    input_path = Path(args.input)
    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    records = [json.loads(line) for line in input_path.read_text(encoding="utf-8").strip().splitlines()]
    raw_formulas = parse_appell_pages(records, page_range=(args.start_page, args.end_page))

    if args.raw_output:
        raw_path = Path(args.raw_output)
        raw_path.parent.mkdir(parents=True, exist_ok=True)
        with raw_path.open("w", encoding="utf-8") as out:
            for f in raw_formulas:
                out.write(json.dumps(f, ensure_ascii=False) + "\n")
        print(f"Wrote {len(raw_formulas)} raw Appell formulas to {raw_path}")

    resolved = resolve_appell_formulas(raw_formulas)

    with output_path.open("w", encoding="utf-8") as out:
        for f in resolved:
            out.write(json.dumps(f, ensure_ascii=False) + "\n")

    print(f"Resolved {len(resolved)}/{len(raw_formulas)} Appell formulas to {output_path}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())