File size: 51,870 Bytes
48cf766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
"""
Process raw XBRL company facts into structured annual and quarterly financial data.
Supports both US-GAAP and IFRS (ifrs-full) filers (ADRs filing 20-F/6-K).
"""

from datetime import datetime, timedelta
from config import (
    SCALE_FACTOR, ANNUAL_MIN_DAYS, ANNUAL_MAX_DAYS,
    QUARTERLY_MIN_DAYS, QUARTERLY_MAX_DAYS,
    SEMI_ANNUAL_MIN_DAYS, SEMI_ANNUAL_MAX_DAYS,
)
from xbrl_mapper import IS_CONCEPTS, BS_CONCEPTS, CF_CONCEPTS, get_all_concepts

# ── IFRS β†’ US-GAAP concept translation ─────────────────────────
# Maps each SMB universal code to a list of ifrs-full concept names to try
# (in priority order). When an IFRS filer is detected, we copy IFRS data
# into a synthetic us-gaap dict keyed by the first us-gaap concept name
# that xbrl_mapper expects, so all downstream code works unchanged.
IFRS_CONCEPT_MAP = {
    # ── Income Statement ──────────────────────────────────────
    "IS-1000": ["Revenue", "RevenueFromSaleOfGoods", "RevenueFromRenderingOfServices",
                "RevenueFromContractsWithCustomers"],
    "IS-2000": ["CostOfSales"],
    "IS-3000": ["GrossProfit"],
    "IS-4000": ["SellingGeneralAndAdministrativeExpense", "AdministrativeExpense",
                "DistributionCosts", "SellingExpense"],
    "IS-4100": ["SellingExpense"],
    "IS-4200": ["ResearchAndDevelopmentExpense"],
    "IS-4300": ["AdministrativeExpense", "GeneralAndAdministrativeExpense"],
    "IS-5000": ["DepreciationAndAmortisationExpense", "DepreciationExpense",
                "AmortisationExpense"],
    "IS-5500": ["RestructuringProvision", "RestructuringAndRelatedCostIncurredCost"],
    "IS-6000": [],  # IFRS typically doesn't report a single total opex line
    "IS-7000": ["ProfitLossFromOperatingActivities", "OperatingProfit"],
    "IS-7100": ["InterestRevenueCalculatedUsingEffectiveInterestMethod",
                "InterestRevenue", "FinanceIncome"],
    "IS-7200": ["InterestExpense", "FinanceCosts"],
    "IS-7300": ["OtherFinanceIncome", "OtherNonoperatingIncomeExpense"],
    "IS-8000": ["ProfitLossBeforeTax"],
    "IS-8500": ["IncomeTaxExpenseContinuingOperations", "TaxExpenseBenefitOnIncomeLossFromContinuingOperations",
                "IncomeTaxExpense"],
    "IS-9000": ["ProfitLoss", "ProfitLossAttributableToOwnersOfParent"],
    "IS-9500": ["BasicEarningsLossPerShare"],
    "IS-9600": ["DilutedEarningsLossPerShare"],
    "IS-9700": [],  # Shares β€” typically in dei namespace
    "IS-9800": [],
    "IS-SBC": ["SharebasedPaymentExpense", "ShareBasedPaymentArrangementExpense"],

    # ── Balance Sheet ─────────────────────────────────────────
    "BS-1100": ["CashAndCashEquivalents", "Cash"],
    "BS-1200": ["OtherCurrentFinancialAssets", "CurrentFinancialAssetsAtFairValueThroughProfitOrLoss"],
    "BS-1300": ["TradeAndOtherCurrentReceivables", "CurrentTradeReceivables"],
    "BS-1400": ["Inventories", "CurrentInventories"],
    "BS-1500": ["CurrentPrepaidExpenses", "OtherCurrentAssets", "OtherCurrentNonfinancialAssets"],
    "BS-1900": ["CurrentAssets"],
    "BS-2100": ["PropertyPlantAndEquipment"],
    "BS-2200": ["RightofuseAssets"],
    "BS-2300": ["Goodwill"],
    "BS-2400": ["IntangibleAssetsOtherThanGoodwill", "OtherIntangibleAssets"],
    "BS-2500": ["NoncurrentFinancialAssets", "NoncurrentInvestments",
                "OtherNoncurrentFinancialAssets"],
    "BS-2600": ["OtherNoncurrentAssets", "OtherNoncurrentNonfinancialAssets"],
    "BS-2900": ["Assets"],
    "BS-3100": ["TradeAndOtherCurrentPayables", "CurrentTradePayables"],
    "BS-3200": ["CurrentPortionOfNoncurrentBorrowings", "ShorttermBorrowings",
                "CurrentBorrowings"],
    "BS-3300": ["CurrentProvisions", "OtherCurrentLiabilities",
                "OtherCurrentFinancialLiabilities"],
    "BS-3400": ["ContractLiabilities", "DeferredIncomeCurrent"],
    "BS-3500": ["CurrentLeaseLiabilities"],
    "BS-3900": ["CurrentLiabilities"],
    "BS-4100": ["NoncurrentPortionOfNoncurrentBorrowings", "NoncurrentBorrowings",
                "Borrowings"],
    "BS-4200": ["NoncurrentLeaseLiabilities"],
    "BS-4300": ["OtherNoncurrentLiabilities", "NoncurrentProvisions",
                "OtherNoncurrentFinancialLiabilities"],
    "BS-4900": ["Liabilities"],
    "BS-6100": ["IssuedCapital", "SharePremium"],
    "BS-6200": ["RetainedEarnings"],
    "BS-6300": ["TreasuryShares"],
    "BS-6400": ["OtherReserves", "ReserveOfExchangeDifferencesOnTranslation"],
    "BS-6900": ["Equity", "EquityAttributableToOwnersOfParent"],
    "BS-7000": ["EquityAndLiabilities"],

    # ── Cash Flow ─────────────────────────────────────────────
    "CF-1000": ["ProfitLoss", "ProfitLossAttributableToOwnersOfParent"],
    "CF-1100": ["DepreciationAndAmortisationExpense", "DepreciationExpense",
                "AdjustmentsForDepreciationAndAmortisationExpense"],
    "CF-1200": ["SharebasedPaymentExpense", "ShareBasedPaymentArrangementExpense"],
    "CF-1300": ["AdjustmentsForDeferredTax", "DeferredTaxExpenseIncome"],
    "CF-1400": ["OtherNoncashIncomeExpense", "AdjustmentsForNoncashItems"],
    "CF-2100": ["AdjustmentsForDecreaseIncreaseInTradeAccountReceivable",
                "DecreaseIncreaseInTradeAndOtherReceivables"],
    "CF-2200": ["AdjustmentsForDecreaseIncreaseInInventories",
                "DecreaseIncreaseInInventories"],
    "CF-2300": ["AdjustmentsForIncreaseDecreaseInTradeAccountPayable",
                "IncreaseDecreaseInTradeAndOtherPayables"],
    "CF-2400": ["AdjustmentsForIncreaseDecreaseInOtherOperatingCapital",
                "OtherInflowsOutflowsOfCashClassifiedAsOperatingActivities"],
    "CF-3000": ["CashFlowsFromUsedInOperatingActivities"],
    "CF-4100": ["PurchaseOfPropertyPlantAndEquipmentClassifiedAsInvestingActivities",
                "AdditionsOtherThanThroughBusinessCombinationsPropertyPlantAndEquipment"],
    "CF-4200": ["CashFlowsUsedInObtainingControlOfSubsidiariesOrOtherBusinessesClassifiedAsInvestingActivities",
                "AcquisitionOfBusinessesNetOfCashAcquired"],
    "CF-4300": ["PurchaseOfInvestmentsOtherThanInvestmentsAccountedForUsingEquityMethod",
                "PurchaseOfFinancialAssets"],
    "CF-4400": ["ProceedsFromSalesOfInvestmentsOtherThanInvestmentsAccountedForUsingEquityMethod",
                "ProceedsFromSalesOfFinancialAssets"],
    "CF-4500": ["OtherInflowsOutflowsOfCashClassifiedAsInvestingActivities"],
    "CF-4900": ["CashFlowsFromUsedInInvestingActivities"],
    "CF-5100": ["ProceedsFromBorrowingsClassifiedAsFinancingActivities",
                "ProceedsFromIssuanceOfDebt"],
    "CF-5200": ["RepaymentsOfBorrowingsClassifiedAsFinancingActivities",
                "RepaymentsOfBorrowings"],
    "CF-5300": ["PurchaseOfTreasurySharesClassifiedAsFinancingActivities",
                "PaymentsToAcquireOrRedeemEntitysShares"],
    "CF-5400": ["DividendsPaidClassifiedAsFinancingActivities", "DividendsPaid"],
    "CF-5500": ["ProceedsFromIssuingShares"],
    "CF-5600": ["OtherInflowsOutflowsOfCashClassifiedAsFinancingActivities"],
    "CF-5900": ["CashFlowsFromUsedInFinancingActivities"],
    "CF-6000": ["EffectOfExchangeRateChangesOnCashAndCashEquivalents"],
    "CF-6100": ["IncreaseDecreaseInCashAndCashEquivalents",
                "IncreaseDecreaseInCashAndCashEquivalentsBeforeEffectOfExchangeRateChanges"],
    "CF-6200": ["CashAndCashEquivalents"],  # instant β€” beginning balance
    "CF-6300": ["CashAndCashEquivalents"],  # instant β€” ending balance
}


class DataProcessor:
    """Processes raw SEC XBRL data into structured financial statements."""

    def __init__(self, company_facts: dict, submissions: dict):
        self.facts = company_facts
        self.submissions = submissions
        self.entity_name = company_facts.get("entityName", "Unknown")
        self.cik = company_facts.get("cik", 0)

        # Parse fiscal year end from submissions
        fye = submissions.get("fiscalYearEnd", "1231")
        self.fiscal_year_end_month = int(fye[:2])
        self.fiscal_year_end_day = int(fye[2:])

        self.sic = submissions.get("sic", "")
        self.sic_desc = submissions.get("sicDescription", "")

        # Detect IFRS vs US-GAAP
        raw_usgaap = self.facts.get("facts", {}).get("us-gaap", {})
        self.ifrs = self.facts.get("facts", {}).get("ifrs-full", {})
        self.is_ifrs = len(self.ifrs) > 0 and len(raw_usgaap) == 0
        self.dei = self.facts.get("facts", {}).get("dei", {})

        if self.is_ifrs:
            # Detect filing currency (may not be USD)
            self.filing_currency = self._detect_ifrs_currency()
            # Build synthetic us-gaap namespace from IFRS data
            self.usgaap = self._build_usgaap_from_ifrs()
        else:
            self.filing_currency = "USD"
            self.usgaap = raw_usgaap

    def _detect_ifrs_currency(self) -> str:
        """Detect the primary filing currency for an IFRS filer.
        Checks a few high-level concepts for which currency units are present."""
        for probe in ("Revenue", "ProfitLoss", "Assets", "CashAndCashEquivalents"):
            concept_data = self.ifrs.get(probe, {})
            units = concept_data.get("units", {})
            if "USD" in units:
                return "USD"
            # Return first non-per-share currency found
            for unit_key in units:
                if "/" not in unit_key:  # skip "USD/shares" etc.
                    return unit_key
        return "USD"  # fallback

    def _build_usgaap_from_ifrs(self) -> dict:
        """Translate IFRS facts into a synthetic us-gaap dict.
        For each SMB code, find the first matching IFRS concept and store
        its data under the first us-gaap concept name that xbrl_mapper expects.
        All downstream code then works unchanged."""
        all_concepts = get_all_concepts()
        synthetic = {}
        currency = self.filing_currency

        for code, cdef in all_concepts.items():
            ifrs_names = IFRS_CONCEPT_MAP.get(code, [])
            if not ifrs_names:
                continue

            # Target: the first us-gaap concept name xbrl_mapper would look for
            target_gaap_name = cdef["concepts"][0]

            for ifrs_name in ifrs_names:
                ifrs_data = self.ifrs.get(ifrs_name, {})
                if not ifrs_data:
                    continue

                units = ifrs_data.get("units", {})
                # Try filing currency first, then USD
                entries = units.get(currency, [])
                if not entries and currency != "USD":
                    entries = units.get("USD", [])

                # For per-share concepts, try currency/shares patterns
                unit_type = cdef.get("unit", "")
                if unit_type == "USD/shares":
                    entries = units.get(f"{currency}/shares", [])
                    if not entries:
                        entries = units.get("USD/shares", [])
                    if not entries:
                        # Try bare per-share keys
                        for k in units:
                            if "/shares" in k.lower():
                                entries = units[k]
                                break
                elif unit_type == "shares" or cdef.get("scale_shares"):
                    entries = units.get("shares", [])
                    if not entries:
                        entries = units.get("pure", [])

                if entries:
                    # Store under the target gaap name so _resolve_concept finds it
                    if target_gaap_name not in synthetic:
                        synthetic[target_gaap_name] = {
                            "label": ifrs_data.get("label", cdef.get("label", "")),
                            "units": {},
                        }
                    # Determine which unit key to store under
                    if unit_type == "USD/shares":
                        store_key = "USD/shares"
                    elif unit_type == "shares" or cdef.get("scale_shares"):
                        store_key = "shares"
                    else:
                        store_key = "USD"
                    synthetic[target_gaap_name]["units"][store_key] = entries
                    break  # first matching IFRS concept wins

        return synthetic

    def _get_concept_entries(self, concept_name: str, unit_type="USD"):
        """Get all entries for a given XBRL concept and unit."""
        concept_data = self.usgaap.get(concept_name, {})
        units = concept_data.get("units", {})
        return units.get(unit_type, [])

    def _parse_date(self, date_str: str):
        """Parse date string to datetime."""
        if not date_str:
            return None
        try:
            return datetime.strptime(date_str, "%Y-%m-%d")
        except ValueError:
            return None

    def _duration_days(self, entry: dict) -> int:
        """Calculate duration in days for an entry."""
        start = self._parse_date(entry.get("start", ""))
        end = self._parse_date(entry.get("end", ""))
        if start and end:
            return (end - start).days
        return 0

    def _is_annual(self, entry: dict) -> bool:
        """Check if entry represents an annual period."""
        d = self._duration_days(entry)
        return ANNUAL_MIN_DAYS <= d <= ANNUAL_MAX_DAYS

    def _is_quarterly(self, entry: dict) -> bool:
        """Check if entry represents a quarterly period."""
        d = self._duration_days(entry)
        return QUARTERLY_MIN_DAYS <= d <= QUARTERLY_MAX_DAYS

    def _is_semi_annual(self, entry: dict) -> bool:
        """Check if entry represents a semi-annual (~180 day) period."""
        d = self._duration_days(entry)
        return SEMI_ANNUAL_MIN_DAYS <= d <= SEMI_ANNUAL_MAX_DAYS

    def _is_quarterly_or_semi_annual(self, entry: dict) -> bool:
        """Accept both quarterly (80-100d) and semi-annual (170-190d) periods."""
        return self._is_quarterly(entry) or self._is_semi_annual(entry)

    def _get_fiscal_year(self, entry: dict) -> int:
        """Extract fiscal year from entry."""
        fy = entry.get("fy")
        if fy:
            return int(fy)
        # Fallback: use end date
        end = self._parse_date(entry.get("end", ""))
        if end:
            return end.year
        return 0

    def _get_fiscal_period(self, entry: dict) -> str:
        """Extract fiscal period (FY, Q1, Q2, Q3, Q4)."""
        return entry.get("fp", "")

    def _resolve_concept(self, concept_def: dict, entries_filter, unit_type="USD"):
        """
        Try each concept name in priority order and MERGE across all variants.

        Earlier concepts in the list have priority: if concept A already
        populated FY2022, concept B will not overwrite it even if concept B
        has a more recent filing date. Within the SAME concept name,
        most-recently-filed wins (handles restatements / amendments).

        This handles the common case where a company switches XBRL tags
        mid-history (e.g., Revenues β†’ RevenueFromContractWithCustomer
        after ASC 606 adoption). Each concept fills the years the others
        missed, producing a complete time series.
        """
        concepts_list = concept_def["concepts"]
        merged = {}            # (fy, fp) -> entry
        merged_concept = {}    # (fy, fp) -> concept_index (priority tracking)
        primary_concept = None

        for concept_idx, concept_name in enumerate(concepts_list):
            entries = self._get_concept_entries(concept_name, unit_type)
            if not entries:
                continue

            filtered = [e for e in entries if entries_filter(e)]
            if not filtered:
                continue

            if primary_concept is None:
                primary_concept = concept_name

            # Deduplicate: for each entry, derive the fiscal year from
            # the END date (most reliable) and keep most-recently-filed
            # within the same concept priority tier.
            for e in filtered:
                end_date = self._parse_date(e.get("end", ""))
                if not end_date:
                    continue

                # Determine the fiscal year this entry actually belongs to.
                # Use end-date year, adjusted if fiscal year doesn't end Dec 31.
                fy_month = self.fiscal_year_end_month
                if fy_month != 12:
                    # E.g., Apple FYE Sep: entry ending Sep 2023 β†’ FY2023
                    if end_date.month <= fy_month:
                        actual_fy = end_date.year
                    else:
                        actual_fy = end_date.year + 1
                else:
                    actual_fy = end_date.year

                fp = self._get_fiscal_period(e)
                if not fp:
                    fp = "FY" if self._is_annual(e) else ""
                key = (actual_fy, fp)
                filed = e.get("filed", "")

                prev_idx = merged_concept.get(key)
                if prev_idx is None:
                    # No data for this period yet β€” take it
                    merged[key] = e
                    merged[key]["_actual_fy"] = actual_fy
                    merged_concept[key] = concept_idx
                elif concept_idx == prev_idx and filed > merged[key]["filed"]:
                    # Same concept, more recent filing β€” update (restatement)
                    merged[key] = e
                    merged[key]["_actual_fy"] = actual_fy
                # If concept_idx > prev_idx, skip β€” higher-priority concept
                # already populated this period.

        if merged:
            # Re-key with actual_fy; carry match metadata
            result = {}
            match_info = {}
            for orig_key, e in merged.items():
                fy = e.get("_actual_fy", self._get_fiscal_year(e))
                fp = orig_key[1]
                new_key = (fy, fp)
                result[new_key] = e
                cidx = merged_concept.get(orig_key, 0)
                match_info[new_key] = {
                    "concept_idx": cidx,
                    "concept_name": concepts_list[cidx] if cidx < len(concepts_list) else concepts_list[0],
                    "total_candidates": len(concepts_list),
                }
            return primary_concept or concepts_list[0], result, match_info

        return None, {}, {}

    def _resolve_instant_concept(self, concept_def: dict, period_type="end"):
        """
        Resolve an instant (balance sheet) concept.
        Merges data across concept name variants so older eras
        (which may use different XBRL tags) still populate.

        Earlier concepts in the list have priority: if concept A already
        populated a date, concept B will not overwrite it. Within the
        same concept, most-recently-filed wins (restatements/amendments).

        Key insight: each 10-K filing reports TWO balance-sheet dates
        (current year and prior-year comparative), both tagged with the
        same fy. We key by end-date to avoid mixing comparatives with
        current-year values, then map end-dates to fiscal years.
        """
        concepts_list = concept_def["concepts"]
        # Key by end_date (string) -> entry  (priority-aware)
        by_end_date = {}
        by_end_date_priority = {}  # (end_str, fp) -> concept_idx
        primary_concept = None

        for concept_idx, concept_name in enumerate(concepts_list):
            entries = self._get_concept_entries(concept_name)
            if not entries:
                continue

            # Instant items have 'end' but no 'start'
            instant_entries = [e for e in entries
                              if not e.get("start") and e.get("end")
                              and e.get("form") in ("10-K", "10-Q", "10-K/A", "10-Q/A", "20-F", "20-F/A", "6-K", "6-K/A")]

            if not instant_entries:
                # Some entries have both start and end for instant items
                instant_entries = [e for e in entries
                                   if e.get("end")
                                   and e.get("form") in ("10-K", "10-Q", "10-K/A", "10-Q/A", "20-F", "20-F/A", "6-K", "6-K/A")]

            if not instant_entries:
                continue

            if primary_concept is None:
                primary_concept = concept_name

            for e in instant_entries:
                end_str = e.get("end", "")
                fp = self._get_fiscal_period(e)
                key = (end_str, fp)
                filed = e.get("filed", "")

                prev_idx = by_end_date_priority.get(key)
                if prev_idx is None:
                    by_end_date[key] = e
                    by_end_date_priority[key] = concept_idx
                elif concept_idx == prev_idx and filed > by_end_date[key]["filed"]:
                    by_end_date[key] = e

        if not by_end_date:
            return None, {}, {}

        # Now map end_date -> fiscal year using our FYE logic
        merged = {}  # (fy, fp) -> entry
        merged_priority = {}  # (fy, fp) -> concept_idx
        fy_month = self.fiscal_year_end_month
        for (end_str, fp), e in by_end_date.items():
            end_date = self._parse_date(end_str)
            if not end_date:
                continue
            # Determine fiscal year from the end_date
            if fy_month != 12:
                if end_date.month <= fy_month:
                    actual_fy = end_date.year
                else:
                    actual_fy = end_date.year + 1
            else:
                actual_fy = end_date.year

            key = (actual_fy, fp)
            filed = e.get("filed", "")
            if key not in merged or filed > merged[key]["filed"]:
                merged[key] = e
                merged[key]["_actual_fy"] = actual_fy
                merged_priority[key] = by_end_date_priority.get((end_str, fp), 0)

        # Re-key with actual_fy; carry match metadata
        result = {}
        match_info = {}
        for orig_key, e in merged.items():
            fy = e.get("_actual_fy", self._get_fiscal_year(e))
            fp = orig_key[1]
            new_key = (fy, fp)
            result[new_key] = e
            cidx = merged_priority.get(orig_key, 0)
            match_info[new_key] = {
                "concept_idx": cidx,
                "concept_name": concepts_list[cidx] if cidx < len(concepts_list) else concepts_list[0],
                "total_candidates": len(concepts_list),
            }

        return primary_concept or concepts_list[0], result, match_info

    def _build_confidence_entry(self, code, cdef, match_info_for_period=None):
        """Build a confidence_map entry for a line item.

        Args:
            code: line item code (e.g. "IS-1000")
            cdef: concept definition from xbrl_mapper
            match_info_for_period: dict with concept_idx, concept_name,
                total_candidates from the resolve call (None if no XBRL match)

        Returns:
            dict with confidence metadata
        """
        has_formula = bool(cdef.get("formula"))

        if match_info_for_period is None:
            # No XBRL match found
            if has_formula:
                return {
                    "confidence": "derived",
                    "concept_matched": None,
                    "match_position": None,
                    "total_candidates": len(cdef.get("concepts", [])),
                    "is_formula": True,
                    "formula": cdef["formula"],
                    "source": "formula",
                }
            return {
                "confidence": "fallback",
                "concept_matched": None,
                "match_position": None,
                "total_candidates": len(cdef.get("concepts", [])),
                "is_formula": False,
                "source": "default",
            }

        cidx = match_info_for_period["concept_idx"]
        cname = match_info_for_period["concept_name"]
        total = match_info_for_period["total_candidates"]

        # primary = matched on 1st or 2nd concept (idx 0 or 1)
        # secondary = matched on 3rd+ concept (idx >= 2)
        if cidx <= 1:
            confidence = "primary"
        else:
            confidence = "secondary"

        return {
            "confidence": confidence,
            "concept_matched": cname,
            "match_position": cidx + 1,  # 1-based
            "total_candidates": total,
            "is_formula": has_formula,
            "source": "xbrl",
        }

    def extract_annual_data(self) -> dict:
        """
        Extract all annual financial data.
        Returns: {
            "years": [2019, 2020, ...],
            "is_data": {"IS-1000": {2019: val, 2020: val, ...}, ...},
            "bs_data": {"BS-1100": {2019: val, ...}, ...},
            "cf_data": {"CF-1000": {2019: val, ...}, ...},
            "concept_map": {"IS-1000": "RevenueFromContract...", ...},
            "confidence_map": {"IS-1000": {"confidence": "primary", ...}, ...},
        }
        """
        is_data, bs_data, cf_data = {}, {}, {}
        concept_map = {}
        confidence_map = {}
        all_years = set()

        # ── Income Statement (duration-based, annual) ──
        for code, cdef in IS_CONCEPTS.items():
            unit = "USD"
            if cdef.get("unit") == "USD/shares":
                unit = "USD/shares"
            elif cdef.get("unit") == "shares" or cdef.get("scale_shares"):
                unit = "shares"

            def annual_filter(e):
                return (self._is_annual(e) and
                        e.get("form") in ("10-K", "10-K/A", "S-1", "20-F", "20-F/A"))

            concept_name, by_period, match_info = self._resolve_concept(cdef, annual_filter, unit)
            if concept_name:
                concept_map[code] = concept_name
                is_data[code] = {}
                # Use first available match_info entry for code-level confidence
                first_mi = next(iter(match_info.values()), None)
                confidence_map[code] = self._build_confidence_entry(code, cdef, first_mi)
                for (fy, fp), entry in by_period.items():
                    val = entry["val"]
                    if unit == "USD":
                        val = val / SCALE_FACTOR
                        val *= cdef.get("sign", 1)
                    elif cdef.get("scale_shares"):
                        val = val / SCALE_FACTOR  # millions
                    is_data[code][fy] = val
                    all_years.add(fy)
            elif cdef.get("formula"):
                # No XBRL match but has formula β€” mark as derived
                confidence_map[code] = self._build_confidence_entry(code, cdef, None)

        # ── Balance Sheet (instant, annual 10-K year-end) ──
        for code, cdef in BS_CONCEPTS.items():
            concept_name, by_period, match_info = self._resolve_instant_concept(cdef)
            if concept_name:
                concept_map[code] = concept_name
                bs_data[code] = {}
                first_mi = next(iter(match_info.values()), None)
                confidence_map[code] = self._build_confidence_entry(code, cdef, first_mi)
                for (fy, fp), entry in by_period.items():
                    # Only take FY (year-end) values for annual
                    if fp != "FY":
                        continue
                    val = entry["val"] / SCALE_FACTOR * cdef.get("sign", 1)
                    bs_data[code][fy] = val
                    all_years.add(fy)

        # ── Cash Flow (duration-based, annual) ──
        for code, cdef in CF_CONCEPTS.items():
            ctype = cdef["type"]

            if ctype == "duration":
                def annual_cf_filter(e):
                    return (self._is_annual(e) and
                            e.get("form") in ("10-K", "10-K/A", "S-1", "20-F", "20-F/A"))
                concept_name, by_period, match_info = self._resolve_concept(cdef, annual_cf_filter)
            elif ctype in ("instant_start", "instant_end"):
                concept_name, by_period, match_info = self._resolve_instant_concept(cdef)
            else:
                continue

            if concept_name:
                concept_map[code] = concept_name
                cf_data[code] = {}
                first_mi = next(iter(match_info.values()), None)
                confidence_map[code] = self._build_confidence_entry(code, cdef, first_mi)
                for (fy, fp), entry in by_period.items():
                    if ctype == "duration":
                        # Only take FY-tagged entries for annual CF
                        if fp != "FY":
                            continue
                    elif ctype == "instant_end":
                        if fp != "FY":
                            continue
                    elif ctype == "instant_start":
                        if fp != "FY":
                            continue

                    val = entry["val"] / SCALE_FACTOR * cdef.get("sign", 1)
                    if ctype == "instant_start":
                        # Balance at FYE is the BEGINNING of the next fiscal year
                        cf_data[code][fy + 1] = val
                        # Don't expand year range; let IS/BS determine columns
                    else:
                        cf_data[code][fy] = val
                        all_years.add(fy)

        years = sorted(all_years)

        # ── 52/53-week fiscal year detection ──
        # Retail filers (WMT, COST, TGT, NKE) use 52/53-week calendars.
        # Annual periods are 364 or 371 days instead of 365.
        is_52_53_week = False
        _week_year_periods = []
        # Sample a duration concept (revenue) to check period lengths
        for code in ("IS-1000", "IS-7000", "IS-9000"):
            cdef = IS_CONCEPTS.get(code)
            if not cdef:
                continue
            for concept_name in cdef["concepts"]:
                entries = self._get_concept_entries(concept_name)
                if not entries:
                    continue
                for e in entries:
                    if e.get("form") in ("10-K", "10-K/A") and e.get("fp") == "FY":
                        d = self._duration_days(e)
                        if d in (364, 371):
                            is_52_53_week = True
                            _week_year_periods.append(
                                {"fy": self._get_fiscal_year(e), "days": d,
                                 "weeks": d // 7}
                            )
                if is_52_53_week:
                    break
            if is_52_53_week:
                break

        result = {
            "years": years,
            "is_data": is_data,
            "bs_data": bs_data,
            "cf_data": cf_data,
            "concept_map": concept_map,
            "confidence_map": confidence_map,
        }

        if is_52_53_week:
            result["_is_52_53_week"] = True
            result["_52_53_week_periods"] = _week_year_periods

        # ── Fiscal year end change detection ──
        self._detect_fye_changes(result)

        # ── Preferred stock detection ──
        self._detect_preferred_stock(result)

        # ── Dual-class share structure detection ──
        self._detect_dual_class_shares(result)

        # ── Stub period detection (M&A, FYE change, IPO mid-year) ──
        self._detect_stub_periods(result)

        # ── Limited history flag (spin-off / IPO) ──
        n_years = len(result["years"])
        result["_limited_history"] = n_years < 3
        result["_history_years"] = n_years

        return result

    def _detect_fye_changes(self, annual_data: dict):
        """Detect if the company changed its fiscal year end during the data period.

        Looks at end-date months of annual periods across years. If the month
        changes, a FYE change occurred (e.g., Dec -> Sep transition).
        """
        end_months = {}
        for concept_name in ['Revenues', 'RevenueFromContractWithCustomerExcludingAssessedTax',
                             'NetIncomeLoss', 'ProfitLoss']:
            concept_data = self.usgaap.get(concept_name, {})
            if not concept_data:
                continue
            entries = concept_data.get('units', {}).get('USD', [])
            for e in entries:
                if e.get('fp') == 'FY':
                    end = e.get('end', '')
                    fy = e.get('fy')
                    if end and fy:
                        try:
                            month = int(end.split('-')[1])
                            end_months[fy] = month
                        except (IndexError, ValueError):
                            pass
            if end_months:
                break

        unique_months = set(end_months.values())
        if len(unique_months) > 1:
            annual_data["_fye_change"] = {
                "detected": True,
                "end_months_by_year": end_months,
                "note": f"FYE changed: months {unique_months}",
            }
        else:
            annual_data["_fye_change"] = {"detected": False}

    def _detect_preferred_stock(self, annual_data: dict):
        """Detect whether the company has preferred stock outstanding.

        Checks for non-zero values in preferred-stock-related XBRL concepts.
        If found, downstream writers can note that EPS is adjusted for
        preferred dividends.
        """
        preferred = False
        pref_concepts = [
            'PreferredStockValue', 'PreferredStockValueOutstanding',
            'TemporaryEquityCarryingAmountAttributableToParent',
            'RedeemableNoncontrollingInterestEquityPreferredStockCarryingAmount',
            'DividendsPreferredStock', 'PreferredStockDividendsPerShareDeclared',
        ]
        for concept in pref_concepts:
            concept_data = self.usgaap.get(concept, {})
            if not concept_data:
                continue
            entries = concept_data.get('units', {}).get('USD', [])
            fy_entries = [e for e in entries
                         if e.get('fp') == 'FY' and e.get('val', 0) != 0]
            if fy_entries:
                preferred = True
                break

        annual_data["_has_preferred_stock"] = preferred

    def _detect_dual_class_shares(self, annual_data: dict):
        """Detect dual-class share structures (e.g., GOOG/GOOGL, META, BRK).

        Checks for multiple EPS values per fiscal year (different share classes)
        and for multiple share-count entries with different segments on the same date.
        """
        dual_class = False

        # Check EPS entries for multiple distinct values per FY
        for eps_name in ['EarningsPerShareBasic', 'EarningsPerShareDiluted']:
            eps_concept = self.usgaap.get(eps_name, {})
            if not eps_concept:
                continue
            entries = eps_concept.get('units', {}).get('USD/shares', [])
            fy_entries = [e for e in entries if e.get('fp') == 'FY']
            for fy in set(e.get('fy') for e in fy_entries):
                year_entries = [e for e in fy_entries if e.get('fy') == fy]
                unique_vals = set(e.get('val') for e in year_entries)
                if len(unique_vals) > 2:
                    dual_class = True
                    break
            if dual_class:
                break

        # Also check dei namespace for multiple share class entries on same date
        if not dual_class:
            for concept in ['EntityCommonStockSharesOutstanding']:
                concept_data = self.dei.get(concept, {})
                if not concept_data:
                    continue
                entries = concept_data.get('units', {}).get('shares', [])
                dates = {}
                for e in entries:
                    end = e.get('end', '')
                    seg = e.get('segment', '')
                    if end:
                        dates.setdefault(end, set()).add(str(seg))
                if any(len(segs) > 1 for segs in dates.values()):
                    dual_class = True

        annual_data["_dual_class_shares"] = dual_class

    def _detect_stub_periods(self, annual_data: dict):
        """Flag fiscal years shorter than 340 days as stub periods.

        Stub periods arise from mid-year acquisitions, fiscal year end changes,
        or mid-year IPOs. Growth rates across stub periods are not comparable.
        """
        stubs = []
        for concept_name in ['Revenues', 'RevenueFromContractWithCustomerExcludingAssessedTax',
                             'ProfitLoss', 'NetIncomeLoss']:
            concept_data = self.usgaap.get(concept_name, {})
            if not concept_data:
                continue
            entries = concept_data.get('units', {}).get('USD', [])
            for e in entries:
                if e.get('fp') == 'FY':
                    start = e.get('start', '')
                    end = e.get('end', '')
                    if start and end:
                        try:
                            d1 = datetime.strptime(start, '%Y-%m-%d')
                            d2 = datetime.strptime(end, '%Y-%m-%d')
                            days = (d2 - d1).days
                            fy = e.get('fy')
                            if days < 340 and fy:  # normal FY is 350-380 days
                                stubs.append({
                                    "year": int(fy) if fy else 0,
                                    "days": days,
                                    "start": start,
                                    "end": end,
                                    "note": f"Stub period: {days} days ({start} to {end})",
                                })
                        except (ValueError, TypeError):
                            pass
            if stubs:
                break

        # Deduplicate by year
        seen = set()
        unique_stubs = []
        for s in stubs:
            if s["year"] not in seen:
                seen.add(s["year"])
                unique_stubs.append(s)

        annual_data["_stub_periods"] = unique_stubs

    def extract_quarterly_data(self, annual_data: dict = None) -> dict:
        """
        Extract quarterly financial data.
        Returns same structure as annual but keyed by (year, quarter).
        If annual_data is provided, derives Q4 = FY - Q1 - Q2 - Q3 for IS and CF items.
        """
        is_data, bs_data, cf_data = {}, {}, {}
        concept_map = {}
        all_periods = set()

        # ── Income Statement (quarterly) ──
        for code, cdef in IS_CONCEPTS.items():
            unit = "USD"
            if cdef.get("unit") == "USD/shares":
                unit = "USD/shares"
            elif cdef.get("unit") == "shares" or cdef.get("scale_shares"):
                unit = "shares"

            def qtr_filter(e):
                duration_ok = (self._is_quarterly_or_semi_annual(e)
                               if self.is_ifrs else self._is_quarterly(e))
                return (duration_ok and
                        e.get("form") in ("10-Q", "10-Q/A", "10-K", "10-K/A", "20-F", "20-F/A", "6-K", "6-K/A"))

            concept_name, by_period, _mi = self._resolve_concept(cdef, qtr_filter, unit)
            if concept_name:
                concept_map[code] = concept_name
                is_data[code] = {}
                for (fy, fp), entry in by_period.items():
                    if fp not in ("Q1", "Q2", "Q3", "Q4"):
                        continue
                    val = entry["val"]
                    if unit == "USD":
                        val = val / SCALE_FACTOR
                        val *= cdef.get("sign", 1)
                    elif cdef.get("scale_shares"):
                        val = val / SCALE_FACTOR
                    period_key = f"{fp} {fy}"
                    is_data[code][period_key] = val
                    all_periods.add(period_key)

        # ── Balance Sheet (quarterly) ──
        for code, cdef in BS_CONCEPTS.items():
            concept_name, by_period, _mi = self._resolve_instant_concept(cdef)
            if concept_name:
                concept_map[code] = concept_name
                bs_data[code] = {}
                for (fy, fp), entry in by_period.items():
                    if fp not in ("Q1", "Q2", "Q3", "Q4", "FY"):
                        continue
                    period_key = f"{'Q4' if fp == 'FY' else fp} {fy}"
                    val = entry["val"] / SCALE_FACTOR * cdef.get("sign", 1)
                    bs_data[code][period_key] = val
                    all_periods.add(period_key)

        # ── Cash Flow (quarterly) ──
        # CF items are often cumulative YTD (Q2=6mo, Q3=9mo) not standalone.
        # Capture ALL Q1/Q2/Q3 entries regardless of duration, then convert
        # cumulative to standalone: Q2_std = Q2_cum - Q1, Q3_std = Q3_cum - Q2_cum
        for code, cdef in CF_CONCEPTS.items():
            ctype = cdef["type"]
            if ctype == "duration":
                # Accept any entry tagged Q1/Q2/Q3 from 10-Q/10-K
                def qtr_cf_filter(e):
                    return (e.get("fp") in ("Q1", "Q2", "Q3", "Q4") and
                            e.get("form") in ("10-Q", "10-Q/A", "10-K", "10-K/A", "20-F", "20-F/A", "6-K", "6-K/A") and
                            self._duration_days(e) > 0)
                concept_name, by_period, _mi = self._resolve_concept(cdef, qtr_cf_filter)
            elif ctype in ("instant_start", "instant_end"):
                concept_name, by_period, _mi = self._resolve_instant_concept(cdef)
            else:
                continue

            if concept_name:
                concept_map[code] = concept_name
                cf_data[code] = {}

                if ctype == "duration":
                    # Group entries by fiscal year, detect cumulative vs standalone
                    by_fy = {}
                    for (fy, fp), entry in by_period.items():
                        if fp not in ("Q1", "Q2", "Q3", "Q4"):
                            continue
                        by_fy.setdefault(fy, {})[fp] = entry

                    sign = cdef.get("sign", 1)
                    for fy, qtr_entries in by_fy.items():
                        vals = {}
                        for fp, entry in sorted(qtr_entries.items()):
                            raw = entry["val"] / SCALE_FACTOR * sign
                            days = self._duration_days(entry)
                            vals[fp] = {"raw": raw, "days": days}

                        # Detect cumulative: Q2 duration > 150 days = YTD
                        q2_cum = vals.get("Q2", {}).get("days", 0) > 150
                        q3_cum = vals.get("Q3", {}).get("days", 0) > 250

                        for fp in ("Q1", "Q2", "Q3", "Q4"):
                            if fp not in vals:
                                continue
                            raw = vals[fp]["raw"]
                            if fp == "Q2" and q2_cum and "Q1" in vals:
                                raw = raw - vals["Q1"]["raw"]
                            elif fp == "Q3" and q3_cum and "Q2" in vals:
                                raw = raw - vals["Q2"]["raw"]
                            period_key = f"{fp} {fy}"
                            cf_data[code][period_key] = raw
                            all_periods.add(period_key)
                else:
                    # Instant items (BS-like)
                    for (fy, fp), entry in by_period.items():
                        if fp not in ("Q1", "Q2", "Q3", "Q4", "FY"):
                            continue
                        period_key = f"{'Q4' if fp == 'FY' else fp} {fy}"
                        val = entry["val"] / SCALE_FACTOR * cdef.get("sign", 1)
                        cf_data[code][period_key] = val
                        all_periods.add(period_key)

        # Sort periods chronologically
        def period_sort_key(p):
            parts = p.split()
            qtr = {"Q1": 1, "Q2": 2, "Q3": 3, "Q4": 4}.get(parts[0], 0)
            yr = int(parts[1]) if len(parts) > 1 else 0
            return (yr, qtr)

        periods = sorted(all_periods, key=period_sort_key)

        result = {
            "periods": periods,
            "is_data": is_data,
            "bs_data": bs_data,
            "cf_data": cf_data,
            "concept_map": concept_map,
        }

        # Detect semi-annual reporting (European ADRs: only H1 ~180d, labeled Q2)
        # Check IS data specifically β€” BS has FY snapshots mapped as Q4 which
        # don't indicate quarterly reporting.
        semi_annual = False
        if self.is_ifrs and is_data:
            is_periods = set()
            for code_vals in is_data.values():
                is_periods.update(code_vals.keys())
            if is_periods:
                has_q1 = any("Q1" in p for p in is_periods)
                has_q3 = any("Q3" in p for p in is_periods)
                has_q2 = any("Q2" in p for p in is_periods)
                # Semi-annual: has Q2 (H1) but no Q1 or Q3
                if has_q2 and not has_q1 and not has_q3:
                    semi_annual = True

        self.is_semi_annual = semi_annual

        if semi_annual and annual_data:
            result = self._convert_to_semi_annual(result, annual_data)
        elif annual_data:
            # Derive Q4 = FY - Q1 - Q2 - Q3 for IS and CF duration items
            self._derive_q4(result, annual_data)
            result["_reporting_frequency"] = "quarterly"
        else:
            result["_reporting_frequency"] = "quarterly"

        return result

    def _convert_to_semi_annual(self, qtr_data: dict, annual_data: dict) -> dict:
        """Convert quarterly data with only H1 (~180d, labeled Q2) to H1/H2 semi-annual.

        H1 = the existing Q2 value (the reported 6-month period).
        H2 = FY - H1 for IS and CF duration items.
        BS: H1 uses the interim snapshot; H2 uses FY year-end values.
        """
        new_is, new_bs, new_cf = {}, {}, {}
        new_periods = set()

        for period in qtr_data["periods"]:
            parts = period.split()
            if len(parts) != 2:
                continue
            try:
                year = int(parts[1])
            except ValueError:
                continue

            h1_label = f"H1 {year}"
            h2_label = f"H2 {year}"

            # ── Relabel Q2 β†’ H1 across all sections ──
            for section, dest in [("is_data", new_is), ("bs_data", new_bs), ("cf_data", new_cf)]:
                src = qtr_data[section]
                for code, vals in src.items():
                    if period in vals:
                        if code not in dest:
                            dest[code] = {}
                        dest[code][h1_label] = vals[period]

            new_periods.add(h1_label)

            # ── Derive H2 = FY - H1 for IS duration items ──
            if year in annual_data.get("years", []):
                for code in annual_data.get("is_data", {}):
                    fy_val = annual_data["is_data"][code].get(year)
                    h1_val = qtr_data["is_data"].get(code, {}).get(period)
                    if fy_val is not None and h1_val is not None:
                        if code not in new_is:
                            new_is[code] = {}
                        new_is[code][h2_label] = fy_val - h1_val

                # ── Derive H2 = FY - H1 for CF duration items ──
                for code, cdef in CF_CONCEPTS.items():
                    if cdef["type"] != "duration":
                        continue
                    fy_val = annual_data.get("cf_data", {}).get(code, {}).get(year)
                    h1_val = qtr_data["cf_data"].get(code, {}).get(period)
                    if fy_val is not None and h1_val is not None:
                        if code not in new_cf:
                            new_cf[code] = {}
                        new_cf[code][h2_label] = fy_val - h1_val

                # ── BS H2 = FY year-end snapshot ──
                for code in annual_data.get("bs_data", {}):
                    fy_val = annual_data["bs_data"][code].get(year)
                    if fy_val is not None:
                        if code not in new_bs:
                            new_bs[code] = {}
                        new_bs[code][h2_label] = fy_val

                new_periods.add(h2_label)

        # Sort periods chronologically: H1 before H2, by year
        def semi_sort_key(p):
            parts = p.split()
            half = 1 if parts[0] == "H1" else 2
            yr = int(parts[1]) if len(parts) > 1 else 0
            return (yr, half)

        return {
            "periods": sorted(new_periods, key=semi_sort_key),
            "is_data": new_is,
            "bs_data": new_bs,
            "cf_data": new_cf,
            "concept_map": qtr_data.get("concept_map", {}),
            "_reporting_frequency": "semi_annual",
        }

    def _derive_q4(self, qtr_data: dict, annual_data: dict):
        """Derive Q4 for IS and CF duration items: Q4 = FY_annual - Q1 - Q2 - Q3."""
        # Collect years present in quarterly data
        years_seen = set()
        for period in qtr_data["periods"]:
            parts = period.split()
            if len(parts) == 2:
                try:
                    years_seen.add(int(parts[1]))
                except ValueError:
                    pass

        new_periods = set(qtr_data["periods"])

        for yr in years_seen:
            q1k, q2k, q3k, q4k = f"Q1 {yr}", f"Q2 {yr}", f"Q3 {yr}", f"Q4 {yr}"

            # IS items
            for code, cdef in IS_CONCEPTS.items():
                fy_val = annual_data["is_data"].get(code, {}).get(yr)
                q_data = qtr_data["is_data"].get(code, {})
                q1, q2, q3 = q_data.get(q1k), q_data.get(q2k), q_data.get(q3k)
                if fy_val is not None and q1 is not None and q2 is not None and q3 is not None:
                    if q4k not in q_data:
                        if code not in qtr_data["is_data"]:
                            qtr_data["is_data"][code] = {}
                        qtr_data["is_data"][code][q4k] = fy_val - q1 - q2 - q3
                        new_periods.add(q4k)

            # CF duration items only (BS instant already maps FY→Q4)
            for code, cdef in CF_CONCEPTS.items():
                if cdef["type"] != "duration":
                    continue
                fy_val = annual_data["cf_data"].get(code, {}).get(yr)
                q_data = qtr_data["cf_data"].get(code, {})
                q1, q2, q3 = q_data.get(q1k), q_data.get(q2k), q_data.get(q3k)
                if fy_val is not None and q1 is not None and q2 is not None and q3 is not None:
                    if q4k not in q_data:
                        if code not in qtr_data["cf_data"]:
                            qtr_data["cf_data"][code] = {}
                        qtr_data["cf_data"][code][q4k] = fy_val - q1 - q2 - q3
                        new_periods.add(q4k)

        # Re-sort periods
        def period_sort_key(p):
            parts = p.split()
            qtr = {"Q1": 1, "Q2": 2, "Q3": 3, "Q4": 4}.get(parts[0], 0)
            yr = int(parts[1]) if len(parts) > 1 else 0
            return (yr, qtr)

        qtr_data["periods"] = sorted(new_periods, key=period_sort_key)