datasynth-generators 2.2.0

50+ data generators covering GL, P2P, O2C, S2C, HR, manufacturing, audit, tax, treasury, and ESG
Documentation
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
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
//! Chart of Accounts generator.

use tracing::debug;

use datasynth_core::accounts::{
    cash_accounts, control_accounts, equity_accounts, expense_accounts, liability_accounts,
    revenue_accounts, suspense_accounts, tax_accounts,
};
use datasynth_core::models::*;
use datasynth_core::pcg_loader;
use datasynth_core::skr_loader;
use datasynth_core::traits::Generator;
use datasynth_core::utils::seeded_rng;
use rand_chacha::ChaCha8Rng;

/// Accounting framework for CoA generation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CoAFramework {
    /// US GAAP (4-digit accounts)
    #[default]
    UsGaap,
    /// French GAAP / Plan Comptable Général (6-digit accounts)
    FrenchPcg,
    /// German GAAP / SKR04 (4-digit accounts)
    GermanSkr04,
}

/// Generator for Chart of Accounts.
pub struct ChartOfAccountsGenerator {
    rng: ChaCha8Rng,
    seed: u64,
    complexity: CoAComplexity,
    industry: IndustrySector,
    count: u64,
    /// Accounting framework for CoA generation.
    coa_framework: CoAFramework,
}

impl ChartOfAccountsGenerator {
    /// Create a new CoA generator.
    pub fn new(complexity: CoAComplexity, industry: IndustrySector, seed: u64) -> Self {
        Self {
            rng: seeded_rng(seed, 0),
            seed,
            complexity,
            industry,
            count: 0,
            coa_framework: CoAFramework::UsGaap,
        }
    }

    /// Use French GAAP (Plan Comptable Général) account structure.
    ///
    /// Deprecated: use `with_coa_framework(CoAFramework::FrenchPcg)` instead.
    pub fn with_french_pcg(mut self, use_pcg: bool) -> Self {
        if use_pcg {
            self.coa_framework = CoAFramework::FrenchPcg;
        }
        self
    }

    /// Set the accounting framework for CoA generation.
    pub fn with_coa_framework(mut self, framework: CoAFramework) -> Self {
        self.coa_framework = framework;
        self
    }

    /// Generate a complete chart of accounts.
    pub fn generate(&mut self) -> ChartOfAccounts {
        debug!(
            complexity = ?self.complexity,
            industry = ?self.industry,
            seed = self.seed,
            framework = ?self.coa_framework,
            "Generating chart of accounts"
        );

        self.count += 1;
        match self.coa_framework {
            CoAFramework::UsGaap => self.generate_default(),
            CoAFramework::FrenchPcg => self.generate_pcg(),
            CoAFramework::GermanSkr04 => self.generate_skr(),
        }
    }

    /// Generate default (US-style) chart of accounts.
    fn generate_default(&mut self) -> ChartOfAccounts {
        let target_count = self.complexity.target_count();
        let mut coa = ChartOfAccounts::new(
            format!("COA_{:?}_{}", self.industry, self.complexity.target_count()),
            format!("{:?} Chart of Accounts", self.industry),
            "US".to_string(),
            self.industry,
            self.complexity,
        );

        // Seed canonical accounts first so other generators can find them
        Self::seed_canonical_accounts(&mut coa);

        // Generate additional accounts by type
        self.generate_asset_accounts(&mut coa, target_count / 5);
        self.generate_liability_accounts(&mut coa, target_count / 6);
        self.generate_equity_accounts(&mut coa, target_count / 10);
        self.generate_revenue_accounts(&mut coa, target_count / 5);
        self.generate_expense_accounts(&mut coa, target_count / 4);
        self.generate_suspense_accounts(&mut coa);
        coa
    }

    /// Generate Plan Comptable Général (French GAAP) chart of accounts.
    /// Uses the comprehensive PCG 2024 structure from [arrhes/PCG](https://github.com/arrhes/PCG) when available.
    fn generate_pcg(&mut self) -> ChartOfAccounts {
        match pcg_loader::build_chart_of_accounts_from_pcg_2024(self.complexity, self.industry) {
            Ok(coa) => coa,
            Err(_) => self.generate_pcg_fallback(),
        }
    }

    /// Generate SKR04 (German GAAP) chart of accounts.
    /// Uses the embedded SKR04 2024 structure when available.
    fn generate_skr(&mut self) -> ChartOfAccounts {
        match skr_loader::build_chart_of_accounts_from_skr04(self.complexity, self.industry) {
            Ok(coa) => coa,
            Err(_) => self.generate_skr_fallback(),
        }
    }

    /// Fallback simplified SKR04 when the embedded 2024 JSON cannot be loaded.
    fn generate_skr_fallback(&mut self) -> ChartOfAccounts {
        use datasynth_core::skr;
        let target_count = self.complexity.target_count();
        let mut coa = ChartOfAccounts::new(
            format!("COA_SKR04_{:?}_{}", self.industry, target_count),
            format!("Standardkontenrahmen 04 – {:?}", self.industry),
            "DE".to_string(),
            self.industry,
            self.complexity,
        );
        coa.account_format = "####".to_string();

        // Seed key SKR04 accounts
        let key_accounts = [
            (
                skr::control_accounts::AR_CONTROL,
                "Forderungen aus L+L",
                AccountType::Asset,
                AccountSubType::AccountsReceivable,
            ),
            (
                skr::control_accounts::AP_CONTROL,
                "Verbindlichkeiten aus L+L",
                AccountType::Liability,
                AccountSubType::AccountsPayable,
            ),
            (
                skr::control_accounts::INVENTORY,
                "Vorräte",
                AccountType::Asset,
                AccountSubType::Inventory,
            ),
            (
                skr::control_accounts::FIXED_ASSETS,
                "Sachanlagen",
                AccountType::Asset,
                AccountSubType::FixedAssets,
            ),
            (
                skr::cash_accounts::OPERATING_CASH,
                "Bank",
                AccountType::Asset,
                AccountSubType::Cash,
            ),
            (
                skr::cash_accounts::PETTY_CASH,
                "Kasse",
                AccountType::Asset,
                AccountSubType::Cash,
            ),
            (
                skr::equity_accounts::COMMON_STOCK,
                "Gezeichnetes Kapital",
                AccountType::Equity,
                AccountSubType::CommonStock,
            ),
            (
                skr::equity_accounts::RETAINED_EARNINGS,
                "Gewinnvortrag",
                AccountType::Equity,
                AccountSubType::RetainedEarnings,
            ),
            (
                skr::revenue_accounts::PRODUCT_REVENUE,
                "Umsatzerlöse",
                AccountType::Revenue,
                AccountSubType::ProductRevenue,
            ),
            (
                skr::revenue_accounts::SERVICE_REVENUE,
                "Erlöse Leistungen",
                AccountType::Revenue,
                AccountSubType::ServiceRevenue,
            ),
            (
                skr::expense_accounts::COGS,
                "Materialaufwand",
                AccountType::Expense,
                AccountSubType::CostOfGoodsSold,
            ),
            (
                skr::expense_accounts::SALARIES_WAGES,
                "Löhne und Gehälter",
                AccountType::Expense,
                AccountSubType::OperatingExpenses,
            ),
            (
                skr::expense_accounts::DEPRECIATION,
                "Abschreibungen",
                AccountType::Expense,
                AccountSubType::DepreciationExpense,
            ),
            (
                skr::expense_accounts::RENT,
                "Miete",
                AccountType::Expense,
                AccountSubType::OperatingExpenses,
            ),
        ];

        for (code, name, acc_type, sub_type) in key_accounts {
            let mut account =
                GLAccount::new(code.to_string(), name.to_string(), acc_type, sub_type);
            account.requires_cost_center = acc_type == AccountType::Expense;
            coa.add_account(account);
        }

        // Add additional accounts to reach target count
        let mut num = 4100u32;
        while coa.account_count() < target_count && num < 9900 {
            let code = format!("{num:04}");
            if coa.get_account(&code).is_none() {
                let class = (num / 1000) as u8;
                let (acc_type, sub_type) = match class {
                    0..=1 => (AccountType::Asset, AccountSubType::OtherAssets),
                    2 => (AccountType::Equity, AccountSubType::RetainedEarnings),
                    3 => (AccountType::Liability, AccountSubType::OtherLiabilities),
                    4 => (AccountType::Revenue, AccountSubType::OtherIncome),
                    5 => (AccountType::Expense, AccountSubType::CostOfGoodsSold),
                    6 => (AccountType::Expense, AccountSubType::OperatingExpenses),
                    7 => (AccountType::Expense, AccountSubType::InterestExpense),
                    _ => (AccountType::Asset, AccountSubType::SuspenseClearing),
                };
                coa.add_account(GLAccount::new(
                    code,
                    format!("Konto {num}"),
                    acc_type,
                    sub_type,
                ));
            }
            num += 10;
        }

        coa
    }

    /// Fallback simplified PCG when the embedded 2024 JSON cannot be loaded.
    fn generate_pcg_fallback(&mut self) -> ChartOfAccounts {
        let target_count = self.complexity.target_count();
        let mut coa = ChartOfAccounts::new(
            format!("COA_PCG_{:?}_{}", self.industry, target_count),
            format!("Plan Comptable Général – {:?}", self.industry),
            "FR".to_string(),
            self.industry,
            self.complexity,
        );
        coa.account_format = "######".to_string();

        self.generate_pcg_class_1(&mut coa, target_count / 10);
        self.generate_pcg_class_2(&mut coa, target_count / 6);
        self.generate_pcg_class_3(&mut coa, target_count / 8);
        self.generate_pcg_class_4(&mut coa, target_count / 5);
        self.generate_pcg_class_5(&mut coa, target_count / 12);
        self.generate_pcg_class_6(&mut coa, target_count / 4);
        self.generate_pcg_class_7(&mut coa, target_count / 5);
        self.generate_pcg_class_8(&mut coa);

        coa
    }

    fn generate_pcg_class_1(&mut self, coa: &mut ChartOfAccounts, count: usize) {
        let items = [
            (
                101,
                "Capital",
                AccountType::Equity,
                AccountSubType::CommonStock,
            ),
            (
                129,
                "Résultat",
                AccountType::Equity,
                AccountSubType::RetainedEarnings,
            ),
            (
                164,
                "Emprunts",
                AccountType::Liability,
                AccountSubType::LongTermDebt,
            ),
            (
                151,
                "Provisions pour risques",
                AccountType::Liability,
                AccountSubType::AccruedLiabilities,
            ),
        ];
        for (base, name, acc_type, sub_type) in items {
            for i in 0..count.max(1) {
                let num = base * 1000 + (i as u32 % 100);
                coa.add_account(GLAccount::new(
                    format!("{num:06}"),
                    format!("{} {}", name, i + 1),
                    acc_type,
                    sub_type,
                ));
            }
        }
    }

    fn generate_pcg_class_2(&mut self, coa: &mut ChartOfAccounts, count: usize) {
        for i in 0..count.max(1) {
            let num = 215000 + (i as u32 % 100);
            coa.add_account(GLAccount::new(
                format!("{num:06}"),
                format!("Immobilisations {}", i + 1),
                AccountType::Asset,
                AccountSubType::FixedAssets,
            ));
        }
        for i in 0..(count / 2).max(1) {
            let num = 281000 + (i as u32 % 100);
            coa.add_account(GLAccount::new(
                format!("{num:06}"),
                format!("Amortissements {}", i + 1),
                AccountType::Asset,
                AccountSubType::AccumulatedDepreciation,
            ));
        }
    }

    fn generate_pcg_class_3(&mut self, coa: &mut ChartOfAccounts, count: usize) {
        for i in 0..count.max(1) {
            let num = 310000 + (i as u32 % 1000);
            coa.add_account(GLAccount::new(
                format!("{num:06}"),
                format!("Stocks {}", i + 1),
                AccountType::Asset,
                AccountSubType::Inventory,
            ));
        }
    }

    fn generate_pcg_class_4(&mut self, coa: &mut ChartOfAccounts, count: usize) {
        for i in 0..count.max(1) {
            let num = 411000 + (i as u32 % 1000);
            coa.add_account(GLAccount::new(
                format!("{num:06}"),
                format!("Clients {}", i + 1),
                AccountType::Asset,
                AccountSubType::AccountsReceivable,
            ));
        }
        for i in 0..count.max(1) {
            let num = 401000 + (i as u32 % 1000);
            coa.add_account(GLAccount::new(
                format!("{num:06}"),
                format!("Fournisseurs {}", i + 1),
                AccountType::Liability,
                AccountSubType::AccountsPayable,
            ));
        }
        let clearing = GLAccount::new(
            "408000".to_string(),
            "Fournisseurs – non encore reçus".to_string(),
            AccountType::Liability,
            AccountSubType::GoodsReceivedClearing,
        );
        coa.add_account(clearing);
    }

    fn generate_pcg_class_5(&mut self, coa: &mut ChartOfAccounts, count: usize) {
        let bases = [
            (512, "Banque"),
            (530, "Caisse"),
            (511, "Valeurs à l'encaissement"),
        ];
        for (base, name) in bases {
            for i in 0..(count / 3).max(1) {
                let num = base * 1000 + (i as u32 % 100);
                coa.add_account(GLAccount::new(
                    format!("{num:06}"),
                    format!("{} {}", name, i + 1),
                    AccountType::Asset,
                    AccountSubType::Cash,
                ));
            }
        }
    }

    fn generate_pcg_class_6(&mut self, coa: &mut ChartOfAccounts, count: usize) {
        let bases = [
            (603, "Achats"),
            (641, "Rémunérations"),
            (681, "DAP"),
            (613, "Loyers"),
            (661, "Charges financières"),
        ];
        for (base, name) in bases {
            for i in 0..(count / 5).max(1) {
                let num = base * 1000 + (i as u32 % 100);
                let mut account = GLAccount::new(
                    format!("{num:06}"),
                    format!("{} {}", name, i + 1),
                    AccountType::Expense,
                    AccountSubType::OperatingExpenses,
                );
                account.requires_cost_center = true;
                coa.add_account(account);
            }
        }
    }

    fn generate_pcg_class_7(&mut self, coa: &mut ChartOfAccounts, count: usize) {
        let bases = [
            (701, "Ventes"),
            (706, "Prestations"),
            (758, "Produits divers"),
        ];
        for (base, name) in bases {
            for i in 0..(count / 3).max(1) {
                let num = base * 1000 + (i as u32 % 100);
                coa.add_account(GLAccount::new(
                    format!("{num:06}"),
                    format!("{} {}", name, i + 1),
                    AccountType::Revenue,
                    AccountSubType::ProductRevenue,
                ));
            }
        }
    }

    fn generate_pcg_class_8(&mut self, coa: &mut ChartOfAccounts) {
        coa.add_account(GLAccount::new(
            "808000".to_string(),
            "Comptes spéciaux".to_string(),
            AccountType::Asset,
            AccountSubType::SuspenseClearing,
        ));
    }

    /// Insert all canonical accounts from `datasynth_core::accounts` into the CoA.
    ///
    /// These are the well-known account numbers (4-digit, 1000-9300 range) that
    /// other generators reference. They are added before auto-generated accounts
    /// (which start at 100000+) so there are no collisions.
    fn seed_canonical_accounts(coa: &mut ChartOfAccounts) {
        // --- Cash accounts (1000-series, Asset / Cash) ---
        coa.add_account(GLAccount::new(
            cash_accounts::OPERATING_CASH.to_string(),
            "Operating Cash".to_string(),
            AccountType::Asset,
            AccountSubType::Cash,
        ));
        coa.add_account(GLAccount::new(
            cash_accounts::BANK_ACCOUNT.to_string(),
            "Bank Account".to_string(),
            AccountType::Asset,
            AccountSubType::Cash,
        ));
        coa.add_account(GLAccount::new(
            cash_accounts::PETTY_CASH.to_string(),
            "Petty Cash".to_string(),
            AccountType::Asset,
            AccountSubType::Cash,
        ));
        coa.add_account(GLAccount::new(
            cash_accounts::WIRE_CLEARING.to_string(),
            "Wire Transfer Clearing".to_string(),
            AccountType::Asset,
            AccountSubType::BankClearing,
        ));

        // --- Control accounts (Asset side) ---
        {
            let mut acct = GLAccount::new(
                control_accounts::AR_CONTROL.to_string(),
                "Accounts Receivable Control".to_string(),
                AccountType::Asset,
                AccountSubType::AccountsReceivable,
            );
            acct.is_control_account = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                control_accounts::IC_AR_CLEARING.to_string(),
                "Intercompany AR Clearing".to_string(),
                AccountType::Asset,
                AccountSubType::AccountsReceivable,
            );
            acct.is_control_account = true;
            coa.add_account(acct);
        }
        coa.add_account(GLAccount::new(
            control_accounts::INVENTORY.to_string(),
            "Inventory".to_string(),
            AccountType::Asset,
            AccountSubType::Inventory,
        ));
        coa.add_account(GLAccount::new(
            control_accounts::FIXED_ASSETS.to_string(),
            "Fixed Assets".to_string(),
            AccountType::Asset,
            AccountSubType::FixedAssets,
        ));
        coa.add_account(GLAccount::new(
            control_accounts::ACCUMULATED_DEPRECIATION.to_string(),
            "Accumulated Depreciation".to_string(),
            AccountType::Asset,
            AccountSubType::AccumulatedDepreciation,
        ));

        // --- Tax asset accounts ---
        coa.add_account(GLAccount::new(
            tax_accounts::INPUT_VAT.to_string(),
            "Input VAT".to_string(),
            AccountType::Asset,
            AccountSubType::OtherReceivables,
        ));
        coa.add_account(GLAccount::new(
            tax_accounts::DEFERRED_TAX_ASSET.to_string(),
            "Deferred Tax Asset".to_string(),
            AccountType::Asset,
            AccountSubType::OtherAssets,
        ));

        // --- Liability / Control accounts (2000-series) ---
        {
            let mut acct = GLAccount::new(
                control_accounts::AP_CONTROL.to_string(),
                "Accounts Payable Control".to_string(),
                AccountType::Liability,
                AccountSubType::AccountsPayable,
            );
            acct.is_control_account = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                control_accounts::IC_AP_CLEARING.to_string(),
                "Intercompany AP Clearing".to_string(),
                AccountType::Liability,
                AccountSubType::AccountsPayable,
            );
            acct.is_control_account = true;
            coa.add_account(acct);
        }
        coa.add_account(GLAccount::new(
            tax_accounts::SALES_TAX_PAYABLE.to_string(),
            "Sales Tax Payable".to_string(),
            AccountType::Liability,
            AccountSubType::TaxLiabilities,
        ));
        coa.add_account(GLAccount::new(
            tax_accounts::VAT_PAYABLE.to_string(),
            "VAT Payable".to_string(),
            AccountType::Liability,
            AccountSubType::TaxLiabilities,
        ));
        coa.add_account(GLAccount::new(
            tax_accounts::WITHHOLDING_TAX_PAYABLE.to_string(),
            "Withholding Tax Payable".to_string(),
            AccountType::Liability,
            AccountSubType::TaxLiabilities,
        ));
        coa.add_account(GLAccount::new(
            liability_accounts::ACCRUED_EXPENSES.to_string(),
            "Accrued Expenses".to_string(),
            AccountType::Liability,
            AccountSubType::AccruedLiabilities,
        ));
        coa.add_account(GLAccount::new(
            liability_accounts::ACCRUED_SALARIES.to_string(),
            "Accrued Salaries".to_string(),
            AccountType::Liability,
            AccountSubType::AccruedLiabilities,
        ));
        coa.add_account(GLAccount::new(
            liability_accounts::ACCRUED_BENEFITS.to_string(),
            "Accrued Benefits".to_string(),
            AccountType::Liability,
            AccountSubType::AccruedLiabilities,
        ));
        coa.add_account(GLAccount::new(
            liability_accounts::UNEARNED_REVENUE.to_string(),
            "Unearned Revenue".to_string(),
            AccountType::Liability,
            AccountSubType::DeferredRevenue,
        ));
        coa.add_account(GLAccount::new(
            liability_accounts::SHORT_TERM_DEBT.to_string(),
            "Short-Term Debt".to_string(),
            AccountType::Liability,
            AccountSubType::ShortTermDebt,
        ));
        coa.add_account(GLAccount::new(
            tax_accounts::DEFERRED_TAX_LIABILITY.to_string(),
            "Deferred Tax Liability".to_string(),
            AccountType::Liability,
            AccountSubType::TaxLiabilities,
        ));
        coa.add_account(GLAccount::new(
            liability_accounts::LONG_TERM_DEBT.to_string(),
            "Long-Term Debt".to_string(),
            AccountType::Liability,
            AccountSubType::LongTermDebt,
        ));
        coa.add_account(GLAccount::new(
            liability_accounts::IC_PAYABLE.to_string(),
            "Intercompany Payable".to_string(),
            AccountType::Liability,
            AccountSubType::OtherLiabilities,
        ));
        {
            let mut acct = GLAccount::new(
                control_accounts::GR_IR_CLEARING.to_string(),
                "GR/IR Clearing".to_string(),
                AccountType::Liability,
                AccountSubType::GoodsReceivedClearing,
            );
            acct.is_suspense_account = true;
            coa.add_account(acct);
        }

        // --- Equity accounts (3000-series) ---
        coa.add_account(GLAccount::new(
            equity_accounts::COMMON_STOCK.to_string(),
            "Common Stock".to_string(),
            AccountType::Equity,
            AccountSubType::CommonStock,
        ));
        coa.add_account(GLAccount::new(
            equity_accounts::APIC.to_string(),
            "Additional Paid-In Capital".to_string(),
            AccountType::Equity,
            AccountSubType::AdditionalPaidInCapital,
        ));
        coa.add_account(GLAccount::new(
            equity_accounts::RETAINED_EARNINGS.to_string(),
            "Retained Earnings".to_string(),
            AccountType::Equity,
            AccountSubType::RetainedEarnings,
        ));
        coa.add_account(GLAccount::new(
            equity_accounts::CURRENT_YEAR_EARNINGS.to_string(),
            "Current Year Earnings".to_string(),
            AccountType::Equity,
            AccountSubType::NetIncome,
        ));
        coa.add_account(GLAccount::new(
            equity_accounts::TREASURY_STOCK.to_string(),
            "Treasury Stock".to_string(),
            AccountType::Equity,
            AccountSubType::TreasuryStock,
        ));
        coa.add_account(GLAccount::new(
            equity_accounts::CTA.to_string(),
            "Currency Translation Adjustment".to_string(),
            AccountType::Equity,
            AccountSubType::OtherComprehensiveIncome,
        ));

        // --- Revenue accounts (4000-series) ---
        coa.add_account(GLAccount::new(
            revenue_accounts::PRODUCT_REVENUE.to_string(),
            "Product Revenue".to_string(),
            AccountType::Revenue,
            AccountSubType::ProductRevenue,
        ));
        coa.add_account(GLAccount::new(
            revenue_accounts::SALES_DISCOUNTS.to_string(),
            "Sales Discounts".to_string(),
            AccountType::Revenue,
            AccountSubType::ProductRevenue,
        ));
        coa.add_account(GLAccount::new(
            revenue_accounts::SALES_RETURNS.to_string(),
            "Sales Returns and Allowances".to_string(),
            AccountType::Revenue,
            AccountSubType::ProductRevenue,
        ));
        coa.add_account(GLAccount::new(
            revenue_accounts::SERVICE_REVENUE.to_string(),
            "Service Revenue".to_string(),
            AccountType::Revenue,
            AccountSubType::ServiceRevenue,
        ));
        coa.add_account(GLAccount::new(
            revenue_accounts::IC_REVENUE.to_string(),
            "Intercompany Revenue".to_string(),
            AccountType::Revenue,
            AccountSubType::OtherIncome,
        ));
        coa.add_account(GLAccount::new(
            revenue_accounts::OTHER_REVENUE.to_string(),
            "Other Revenue".to_string(),
            AccountType::Revenue,
            AccountSubType::OtherIncome,
        ));

        // --- Expense accounts (5000-7xxx series) ---
        {
            let mut acct = GLAccount::new(
                expense_accounts::COGS.to_string(),
                "Cost of Goods Sold".to_string(),
                AccountType::Expense,
                AccountSubType::CostOfGoodsSold,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::RAW_MATERIALS.to_string(),
                "Raw Materials".to_string(),
                AccountType::Expense,
                AccountSubType::CostOfGoodsSold,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::DIRECT_LABOR.to_string(),
                "Direct Labor".to_string(),
                AccountType::Expense,
                AccountSubType::CostOfGoodsSold,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::MANUFACTURING_OVERHEAD.to_string(),
                "Manufacturing Overhead".to_string(),
                AccountType::Expense,
                AccountSubType::CostOfGoodsSold,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::DEPRECIATION.to_string(),
                "Depreciation Expense".to_string(),
                AccountType::Expense,
                AccountSubType::DepreciationExpense,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::SALARIES_WAGES.to_string(),
                "Salaries and Wages".to_string(),
                AccountType::Expense,
                AccountSubType::OperatingExpenses,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::BENEFITS.to_string(),
                "Benefits Expense".to_string(),
                AccountType::Expense,
                AccountSubType::OperatingExpenses,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::RENT.to_string(),
                "Rent Expense".to_string(),
                AccountType::Expense,
                AccountSubType::OperatingExpenses,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::UTILITIES.to_string(),
                "Utilities Expense".to_string(),
                AccountType::Expense,
                AccountSubType::OperatingExpenses,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::OFFICE_SUPPLIES.to_string(),
                "Office Supplies".to_string(),
                AccountType::Expense,
                AccountSubType::AdministrativeExpenses,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::TRAVEL_ENTERTAINMENT.to_string(),
                "Travel and Entertainment".to_string(),
                AccountType::Expense,
                AccountSubType::SellingExpenses,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::PROFESSIONAL_FEES.to_string(),
                "Professional Fees".to_string(),
                AccountType::Expense,
                AccountSubType::AdministrativeExpenses,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::INSURANCE.to_string(),
                "Insurance Expense".to_string(),
                AccountType::Expense,
                AccountSubType::OperatingExpenses,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::BAD_DEBT.to_string(),
                "Bad Debt Expense".to_string(),
                AccountType::Expense,
                AccountSubType::OperatingExpenses,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::INTEREST_EXPENSE.to_string(),
                "Interest Expense".to_string(),
                AccountType::Expense,
                AccountSubType::InterestExpense,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::PURCHASE_DISCOUNTS.to_string(),
                "Purchase Discounts".to_string(),
                AccountType::Expense,
                AccountSubType::OtherExpenses,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                expense_accounts::FX_GAIN_LOSS.to_string(),
                "FX Gain/Loss".to_string(),
                AccountType::Expense,
                AccountSubType::ForeignExchangeLoss,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }

        // --- Tax expense (8000-series) ---
        {
            let mut acct = GLAccount::new(
                tax_accounts::TAX_EXPENSE.to_string(),
                "Tax Expense".to_string(),
                AccountType::Expense,
                AccountSubType::TaxExpense,
            );
            acct.requires_cost_center = true;
            coa.add_account(acct);
        }

        // --- Suspense / Clearing accounts (9000-series) ---
        {
            let mut acct = GLAccount::new(
                suspense_accounts::GENERAL_SUSPENSE.to_string(),
                "General Suspense".to_string(),
                AccountType::Asset,
                AccountSubType::SuspenseClearing,
            );
            acct.is_suspense_account = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                suspense_accounts::PAYROLL_CLEARING.to_string(),
                "Payroll Clearing".to_string(),
                AccountType::Asset,
                AccountSubType::SuspenseClearing,
            );
            acct.is_suspense_account = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                suspense_accounts::BANK_RECONCILIATION_SUSPENSE.to_string(),
                "Bank Reconciliation Suspense".to_string(),
                AccountType::Asset,
                AccountSubType::BankClearing,
            );
            acct.is_suspense_account = true;
            coa.add_account(acct);
        }
        {
            let mut acct = GLAccount::new(
                suspense_accounts::IC_ELIMINATION_SUSPENSE.to_string(),
                "IC Elimination Suspense".to_string(),
                AccountType::Asset,
                AccountSubType::IntercompanyClearing,
            );
            acct.is_suspense_account = true;
            coa.add_account(acct);
        }
    }

    fn generate_asset_accounts(&mut self, coa: &mut ChartOfAccounts, count: usize) {
        let sub_types = vec![
            (AccountSubType::Cash, "Cash", 0.15),
            (
                AccountSubType::AccountsReceivable,
                "Accounts Receivable",
                0.20,
            ),
            (AccountSubType::Inventory, "Inventory", 0.15),
            (AccountSubType::PrepaidExpenses, "Prepaid Expenses", 0.10),
            (AccountSubType::FixedAssets, "Fixed Assets", 0.25),
            (
                AccountSubType::AccumulatedDepreciation,
                "Accumulated Depreciation",
                0.10,
            ),
            (AccountSubType::OtherAssets, "Other Assets", 0.05),
        ];

        let mut account_num = 100000u32;
        for (sub_type, name_prefix, weight) in sub_types {
            let sub_count = ((count as f64) * weight).round() as usize;
            for i in 0..sub_count.max(1) {
                let account = GLAccount::new(
                    format!("{account_num}"),
                    format!("{} {}", name_prefix, i + 1),
                    AccountType::Asset,
                    sub_type,
                );
                coa.add_account(account);
                account_num += 10;
            }
        }
    }

    fn generate_liability_accounts(&mut self, coa: &mut ChartOfAccounts, count: usize) {
        let sub_types = vec![
            (AccountSubType::AccountsPayable, "Accounts Payable", 0.25),
            (
                AccountSubType::AccruedLiabilities,
                "Accrued Liabilities",
                0.20,
            ),
            (AccountSubType::ShortTermDebt, "Short-Term Debt", 0.15),
            (AccountSubType::LongTermDebt, "Long-Term Debt", 0.15),
            (AccountSubType::DeferredRevenue, "Deferred Revenue", 0.15),
            (AccountSubType::TaxLiabilities, "Tax Liabilities", 0.10),
        ];

        let mut account_num = 200000u32;
        for (sub_type, name_prefix, weight) in sub_types {
            let sub_count = ((count as f64) * weight).round() as usize;
            for i in 0..sub_count.max(1) {
                let account = GLAccount::new(
                    format!("{account_num}"),
                    format!("{} {}", name_prefix, i + 1),
                    AccountType::Liability,
                    sub_type,
                );
                coa.add_account(account);
                account_num += 10;
            }
        }
    }

    fn generate_equity_accounts(&mut self, coa: &mut ChartOfAccounts, count: usize) {
        let sub_types = vec![
            (AccountSubType::CommonStock, "Common Stock", 0.20),
            (AccountSubType::RetainedEarnings, "Retained Earnings", 0.30),
            (AccountSubType::AdditionalPaidInCapital, "APIC", 0.20),
            (AccountSubType::OtherComprehensiveIncome, "OCI", 0.30),
        ];

        let mut account_num = 300000u32;
        for (sub_type, name_prefix, weight) in sub_types {
            let sub_count = ((count as f64) * weight).round() as usize;
            for i in 0..sub_count.max(1) {
                let account = GLAccount::new(
                    format!("{account_num}"),
                    format!("{} {}", name_prefix, i + 1),
                    AccountType::Equity,
                    sub_type,
                );
                coa.add_account(account);
                account_num += 10;
            }
        }
    }

    fn generate_revenue_accounts(&mut self, coa: &mut ChartOfAccounts, count: usize) {
        let sub_types = vec![
            (AccountSubType::ProductRevenue, "Product Revenue", 0.40),
            (AccountSubType::ServiceRevenue, "Service Revenue", 0.30),
            (AccountSubType::InterestIncome, "Interest Income", 0.10),
            (AccountSubType::OtherIncome, "Other Income", 0.20),
        ];

        let mut account_num = 400000u32;
        for (sub_type, name_prefix, weight) in sub_types {
            let sub_count = ((count as f64) * weight).round() as usize;
            for i in 0..sub_count.max(1) {
                let account = GLAccount::new(
                    format!("{account_num}"),
                    format!("{} {}", name_prefix, i + 1),
                    AccountType::Revenue,
                    sub_type,
                );
                coa.add_account(account);
                account_num += 10;
            }
        }
    }

    fn generate_expense_accounts(&mut self, coa: &mut ChartOfAccounts, count: usize) {
        let sub_types = vec![
            (AccountSubType::CostOfGoodsSold, "COGS", 0.20),
            (
                AccountSubType::OperatingExpenses,
                "Operating Expenses",
                0.25,
            ),
            (AccountSubType::SellingExpenses, "Selling Expenses", 0.15),
            (
                AccountSubType::AdministrativeExpenses,
                "Admin Expenses",
                0.15,
            ),
            (AccountSubType::DepreciationExpense, "Depreciation", 0.10),
            (AccountSubType::InterestExpense, "Interest Expense", 0.05),
            (AccountSubType::TaxExpense, "Tax Expense", 0.05),
            (AccountSubType::OtherExpenses, "Other Expenses", 0.05),
        ];

        let mut account_num = 500000u32;
        for (sub_type, name_prefix, weight) in sub_types {
            let sub_count = ((count as f64) * weight).round() as usize;
            for i in 0..sub_count.max(1) {
                let mut account = GLAccount::new(
                    format!("{account_num}"),
                    format!("{} {}", name_prefix, i + 1),
                    AccountType::Expense,
                    sub_type,
                );
                account.requires_cost_center = true;
                coa.add_account(account);
                account_num += 10;
            }
        }
    }

    fn generate_suspense_accounts(&mut self, coa: &mut ChartOfAccounts) {
        let suspense_types = vec![
            (AccountSubType::SuspenseClearing, "Suspense Clearing"),
            (AccountSubType::GoodsReceivedClearing, "GR/IR Clearing"),
            (AccountSubType::BankClearing, "Bank Clearing"),
            (
                AccountSubType::IntercompanyClearing,
                "Intercompany Clearing",
            ),
        ];

        let mut account_num = 199000u32;
        for (sub_type, name) in suspense_types {
            let mut account = GLAccount::new(
                format!("{account_num}"),
                name.to_string(),
                AccountType::Asset,
                sub_type,
            );
            account.is_suspense_account = true;
            coa.add_account(account);
            account_num += 100;
        }
    }
}

impl Generator for ChartOfAccountsGenerator {
    type Item = ChartOfAccounts;
    type Config = (CoAComplexity, IndustrySector);

    fn new(config: Self::Config, seed: u64) -> Self {
        Self::new(config.0, config.1, seed)
    }

    fn generate_one(&mut self) -> Self::Item {
        self.generate()
    }

    fn reset(&mut self) {
        self.rng = seeded_rng(self.seed, 0);
        self.count = 0;
        self.coa_framework = CoAFramework::UsGaap;
    }

    fn count(&self) -> u64 {
        self.count
    }

    fn seed(&self) -> u64 {
        self.seed
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_small_coa() {
        let mut gen =
            ChartOfAccountsGenerator::new(CoAComplexity::Small, IndustrySector::Manufacturing, 42);
        let coa = gen.generate();

        assert!(coa.account_count() >= 50);
        assert!(!coa.get_suspense_accounts().is_empty());
    }

    #[test]
    fn test_generate_pcg_coa() {
        let mut gen =
            ChartOfAccountsGenerator::new(CoAComplexity::Small, IndustrySector::Manufacturing, 42)
                .with_french_pcg(true);
        let coa = gen.generate();

        assert_eq!(coa.country, "FR");
        assert!(coa.name.contains("Plan Comptable") || coa.name.contains("PCG"));
        assert!(coa.account_count() >= 20);
        // PCG accounts are 6-digit (e.g. 411000, 601000)
        let first = coa.accounts.first().expect("has accounts");
        assert_eq!(first.account_number.len(), 6);
    }

    /// Verifies PCG (Plan Comptable Général) account structure: 6-digit format,
    /// all accounts numeric, and coverage of at least two PCG classes (1–8).
    /// Works for both the embedded PCG 2024 loader and the fallback generator.
    #[test]
    fn test_pcg_account_structure() {
        let mut gen =
            ChartOfAccountsGenerator::new(CoAComplexity::Small, IndustrySector::Manufacturing, 42)
                .with_french_pcg(true);
        let coa = gen.generate();

        assert_eq!(
            coa.account_format, "######",
            "PCG uses 6-digit account format"
        );
        assert!(
            coa.account_count() >= 20,
            "PCG CoA has minimum account count"
        );

        let account_numbers: Vec<_> = coa
            .accounts
            .iter()
            .map(|a| a.account_number.as_str())
            .collect();
        for num in &account_numbers {
            assert_eq!(num.len(), 6, "every PCG account is 6 digits: {}", num);
            assert!(
                num.chars().all(|c| c.is_ascii_digit()),
                "PCG account is numeric: {}",
                num
            );
        }

        // All account numbers must belong to a PCG class (first digit 1–8)
        let first_digits: std::collections::HashSet<char> = account_numbers
            .iter()
            .filter_map(|s| s.chars().next())
            .collect();
        let pcg_classes: std::collections::HashSet<_> =
            ['1', '2', '3', '4', '5', '6', '7', '8'].into();
        assert!(
            !first_digits.is_empty() && first_digits.is_subset(&pcg_classes),
            "PCG account numbers must be in classes 1–8, got first digits: {:?}",
            first_digits
        );
    }
}