x-iztro 0.2.0

Zi Wei Dou Shu (Purple Star Astrology) chart engine, field-for-field identical to iztro
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
//! 运限计算
//!
//! 根据出生星盘和目标日期,计算大限、小限、流年、流月、流日、流时。

use lunar_rust::lunar::LunarRefHelper;
use lunar_rust::{lunar, solar};

use crate::astro::builder::{branch_of, parse_solar_date, stem_of, validate_time_index};
use crate::astro::palace::get_palace_names;
use crate::data::constants::TIGER_RULE;
use crate::data::stars::StarKey;
use crate::data::types::*;
use crate::error::IztroError;
use crate::i18n::{translate_horoscope_name, translate_star};
use crate::models::astrolabe::{Astrolabe, PalaceRef};
use crate::models::horoscope::{
    AgeItem, HoroscopeData, HoroscopeItem, HoroscopeRef, YearlyDecStar, YearlyItem,
};
use crate::models::star::Star;
use crate::models::surpalaces::SurroundedPalaces;
use crate::star::decorative::get_yearly12;
use crate::star::location::{
    get_chang_qu_index_by_stem, get_kui_yue_index, get_lu_yang_tuo_ma_index, get_luan_xi_index,
    get_nianjie_index,
};
use crate::utils::{earthly_branch_to_palace_index, fix_index};

// ============================================================
// 童限宫位映射
// ============================================================

/// 童限宫位名称:在大限未覆盖的童年时期使用
/// 对应 TS: [命宫, 财帛, 疾厄, 夫妻, 福德, 官禄]
const CHILDHOOD_PALACES: [Palace; 6] = [
    Palace::Soul,
    Palace::Wealth,
    Palace::Health,
    Palace::Spouse,
    Palace::Spirit,
    Palace::Career,
];

// ============================================================
// 流耀计算
// ============================================================

/// 获取运限流耀
///
/// 根据给定范围的天干地支,计算流耀在12宫中的分布。
/// 返回12个宫位的星耀列表。
pub fn get_horoscope_stars(
    stem: HeavenlyStem,
    branch: EarthlyBranch,
    scope: Scope,
    lang: Language,
) -> [Vec<Star>; 12] {
    let kui_yue = get_kui_yue_index(stem);
    let chang_qu = get_chang_qu_index_by_stem(stem);
    let lu_yang_tuo_ma = get_lu_yang_tuo_ma_index(stem, branch);
    let luan_xi = get_luan_xi_index(branch);

    let star_keys: (
        StarKey,
        StarKey,
        StarKey,
        StarKey,
        StarKey,
        StarKey,
        StarKey,
        StarKey,
        StarKey,
        StarKey,
    ) = match scope {
        Scope::Decadal => (
            StarKey::Yunkui,
            StarKey::Yunyue,
            StarKey::Yunchang,
            StarKey::Yunqu,
            StarKey::Yunlu,
            StarKey::Yunyang,
            StarKey::Yuntuo,
            StarKey::Yunma,
            StarKey::Yunluan,
            StarKey::Yunxi,
        ),
        Scope::Yearly => (
            StarKey::Liukui,
            StarKey::Liuyue,
            StarKey::Liuchang,
            StarKey::Liuqu,
            StarKey::Liulu,
            StarKey::Liuyang,
            StarKey::Liutuo,
            StarKey::Liuma,
            StarKey::Liuluan,
            StarKey::Liuxi,
        ),
        Scope::Monthly => (
            StarKey::Yuekui,
            StarKey::Yueyue,
            StarKey::Yuechang,
            StarKey::Yuequ,
            StarKey::Yuelu,
            StarKey::Yueyang,
            StarKey::Yuetuo,
            StarKey::Yuema,
            StarKey::Yueluan,
            StarKey::Yuexi,
        ),
        Scope::Daily => (
            StarKey::Rikui,
            StarKey::Riyue,
            StarKey::Richang,
            StarKey::Riqu,
            StarKey::Rilu,
            StarKey::Riyang,
            StarKey::Rituo,
            StarKey::Rima,
            StarKey::Riluan,
            StarKey::Rixi,
        ),
        Scope::Hourly => (
            StarKey::Shikui,
            StarKey::Shiyue,
            StarKey::Shichang,
            StarKey::Shiqu,
            StarKey::Shilu,
            StarKey::Shiyang,
            StarKey::Shituo,
            StarKey::Shima,
            StarKey::Shiluan,
            StarKey::Shixi,
        ),
        // 本命层级取本命星名。iztro 此处把红鸾写成了 `hongluanMin`,
        // 该标识在其 i18n 表中不存在,任何语言下都原样漏成星名;
        // 本命红鸾的标识是 `hongluan`,此处按正确标识安放。
        Scope::Origin => (
            StarKey::TiankuiMin,
            StarKey::TianyueMin,
            StarKey::WenchangMin,
            StarKey::WenquMin,
            StarKey::LucunMin,
            StarKey::QingyangMin,
            StarKey::TuoluoMin,
            StarKey::TianmaMin,
            StarKey::Hongluan,
            StarKey::Tianxi,
        ),
    };

    let mut stars: [Vec<Star>; 12] = std::array::from_fn(|_| Vec::new());

    // 流年范围额外安年解(按流年年支),先于十颗流耀安放
    if scope == Scope::Yearly {
        let nianjie_idx = get_nianjie_index(branch);
        stars[nianjie_idx].push(Star {
            key: StarKey::Nianjie,
            name: translate_star(StarKey::Nianjie, lang).to_string(),
            star_type: StarType::Helper,
            scope: Scope::Yearly,
            brightness: None,
            mutagen: None,
        });
    }

    let placements = [
        (kui_yue.kui, star_keys.0, StarType::Soft),
        (kui_yue.yue, star_keys.1, StarType::Soft),
        (chang_qu.chang, star_keys.2, StarType::Soft),
        (chang_qu.qu, star_keys.3, StarType::Soft),
        (lu_yang_tuo_ma.lu, star_keys.4, StarType::Lucun),
        (lu_yang_tuo_ma.yang, star_keys.5, StarType::Tough),
        (lu_yang_tuo_ma.tuo, star_keys.6, StarType::Tough),
        (lu_yang_tuo_ma.ma, star_keys.7, StarType::Tianma),
        (luan_xi.hongluan, star_keys.8, StarType::Flower),
        (luan_xi.tianxi, star_keys.9, StarType::Flower),
    ];

    for (idx, key, star_type) in placements {
        stars[idx].push(Star {
            key,
            name: translate_star(key, lang).to_string(),
            star_type,
            scope,
            brightness: None,
            mutagen: None,
        });
    }

    stars
}

// ============================================================
// 主函数
// ============================================================

/// 时辰索引转小时数(用于 lunar_rust 日期创建)
fn time_index_to_hour(time_index: u8) -> i64 {
    match time_index {
        0 => 0,
        12 => 23,
        i => (i as i64) * 2 - 1,
    }
}

/// 根据出生星盘和目标阳历日期计算运限
///
/// # 参数
/// - `astrolabe`: 出生星盘
/// - `solar_date`: 目标阳历日期,格式 "YYYY-M-D"(支持 1583-9999 年)
/// - `time_index`: 目标时辰索引 (0=早子, 1=丑, ..., 12=晚子)
/// - `language`: 语言
///
/// # Errors
/// 目标日期非法、目标时辰越界,或 `astrolabe.solar_date` 字段被改为
/// 非法值时返回 [`IztroError`]。
pub fn get_horoscope(
    astrolabe: &Astrolabe,
    solar_date: &str,
    time_index: u8,
    language: Language,
) -> Result<HoroscopeData, IztroError> {
    validate_time_index(time_index)?;

    // ---- 1. 解析出生日期的农历信息 ----
    let (birth_year, birth_month, birth_day) = parse_solar_date(&astrolabe.solar_date)?;

    let birth_hour = time_index_to_hour(astrolabe.time_index);
    let birth_solar = solar::from_ymdhms(birth_year, birth_month, birth_day, birth_hour, 0, 0);
    let birth_lunar = lunar::from_solar(&birth_solar);

    let birthday_lunar_year = birth_lunar.get_year();
    let birthday_lunar_month = birth_lunar.get_month().unsigned_abs() as i32;
    let birthday_lunar_day = birth_lunar.get_day() as u32;
    let birthday_is_leap = birth_lunar.get_month() < 0;

    // ---- 2. 解析目标日期的农历信息 ----
    let (target_year, target_month, target_day) = parse_solar_date(solar_date)?;

    let target_hour = time_index_to_hour(time_index);
    let target_solar = solar::from_ymdhms(target_year, target_month, target_day, target_hour, 0, 0);
    let target_lunar = lunar::from_solar(&target_solar);

    let target_lunar_year = target_lunar.get_year();
    let target_lunar_month_raw = target_lunar.get_month();
    let target_is_leap = target_lunar_month_raw < 0;
    let target_lunar_month = target_lunar_month_raw.unsigned_abs() as i32;
    let target_lunar_day = target_lunar.get_day() as u32;

    // ---- 3. 计算虚岁(分界点由配置决定) ----
    //     自然年分界:跨农历年即加一岁;生日分界:过了农历生日才加一岁
    let mut nominal_age = (target_lunar_year - birthday_lunar_year) as i64;
    match astrolabe.config.age_divide {
        AgeDivide::Normal => nominal_age += 1,
        AgeDivide::Birthday => {
            let passed_birthday = (target_lunar_year == birthday_lunar_year
                && target_lunar_month == birthday_lunar_month
                && target_lunar_day > birthday_lunar_day)
                || target_lunar_month > birthday_lunar_month;
            if passed_birthday {
                nominal_age += 1;
            }
        }
    }
    let nominal_age = nominal_age.max(1) as u32;

    // ---- 4. 目标日期干支四柱(年月分界点由配置决定) ----
    //     初一分界:年按正月初一换年,月按初一以五虎遁推算(闰月下半月归下月);
    //     节气分界:年按立春换年,月按节气精确时刻推算。
    //     日柱晚子时归次日;时柱天干随日柱推算
    let (target_year_gan_str, target_year_zhi_str) = match astrolabe.config.horoscope_divide {
        HoroscopeDivide::Normal => (target_lunar.get_year_gan(), target_lunar.get_year_zhi()),
        HoroscopeDivide::Exact => (
            target_lunar.get_year_gan_by_li_chun(),
            target_lunar.get_year_zhi_by_li_chun(),
        ),
    };
    let target_day_gan_str = target_lunar.get_day_gan_exact();
    let target_day_zhi_str = target_lunar.get_day_zhi_exact();
    let target_time_gan_str = target_lunar.get_time_gan();
    let target_time_zhi_str = target_lunar.get_time_zhi();

    let target_year_stem = stem_of(&target_year_gan_str, "target year")?;
    let target_year_branch = branch_of(&target_year_zhi_str, "target year")?;

    let (target_month_stem, target_month_branch) = match astrolabe.config.horoscope_divide {
        HoroscopeDivide::Normal => {
            let target_month_fix: i32 = if target_is_leap && target_lunar_day > 15 {
                1
            } else {
                0
            };
            (
                HeavenlyStem::from_index(fix_index(
                    TIGER_RULE[target_year_stem.index()].index() as i32 + target_lunar_month - 1
                        + target_month_fix,
                    10,
                )),
                EarthlyBranch::from_index(fix_index(
                    2 + target_lunar_month - 1 + target_month_fix,
                    12,
                )),
            )
        }
        HoroscopeDivide::Exact => {
            let gan = target_lunar.get_month_gan_exact();
            let zhi = target_lunar.get_month_zhi_exact();
            (
                stem_of(&gan, "target month")?,
                branch_of(&zhi, "target month")?,
            )
        }
    };

    let target_day_stem = stem_of(&target_day_gan_str, "target day")?;
    let target_day_branch = branch_of(&target_day_zhi_str, "target day")?;
    let target_time_stem = stem_of(&target_time_gan_str, "target time")?;
    let target_time_branch = branch_of(&target_time_zhi_str, "target time")?;

    // ---- 5. 大限 ----
    //     虚岁落在某宫大限区间内取该宫;尚未起运时为童限,
    //     按虚岁依次落在 命宫/财帛/疾厄/夫妻/福德/官禄,取本命宫位干支
    let (decadal_palace_idx, is_childhood) = find_decadal_palace(astrolabe, nominal_age);
    let (decadal_stem, decadal_branch) = if is_childhood {
        let p = &astrolabe.palaces[decadal_palace_idx];
        (p.heavenly_stem, p.earthly_branch)
    } else {
        let d = &astrolabe.palaces[decadal_palace_idx].decadal;
        (d.heavenly_stem, d.earthly_branch)
    };
    let decadal_mutagen = astrolabe.config.mutagens_of(decadal_stem).to_vec();
    let decadal_palace_names = get_palace_names(decadal_palace_idx).to_vec();
    let decadal_stars = get_horoscope_stars(decadal_stem, decadal_branch, Scope::Decadal, language);

    let decadal = HoroscopeItem {
        index: decadal_palace_idx,
        name: translate_horoscope_name(
            if is_childhood {
                HoroscopeName::Childhood
            } else {
                HoroscopeName::Decadal
            },
            language,
        )
        .to_string(),
        heavenly_stem: decadal_stem,
        earthly_branch: decadal_branch,
        palace_names: decadal_palace_names,
        mutagen: decadal_mutagen,
        stars: Some(decadal_stars.to_vec()),
    };

    // ---- 6. 小限 ----
    let age_palace_idx = find_age_palace(astrolabe, nominal_age);
    let age_stem = astrolabe.palaces[age_palace_idx].heavenly_stem;
    let age_branch = astrolabe.palaces[age_palace_idx].earthly_branch;
    let age_mutagen = astrolabe.config.mutagens_of(age_stem).to_vec();
    let age_palace_names = get_palace_names(age_palace_idx).to_vec();

    let age = AgeItem {
        base: HoroscopeItem {
            index: age_palace_idx,
            name: translate_horoscope_name(HoroscopeName::Age, language).to_string(),
            heavenly_stem: age_stem,
            earthly_branch: age_branch,
            palace_names: age_palace_names,
            mutagen: age_mutagen,
            stars: None,
        },
        nominal_age,
    };

    // ---- 7. 流年(含按目标年支起的岁前/将前十二神) ----
    let yearly_index = earthly_branch_to_palace_index(target_year_branch);
    let yearly_mutagen = astrolabe.config.mutagens_of(target_year_stem).to_vec();
    let yearly_palace_names = get_palace_names(yearly_index).to_vec();
    let yearly_stars = get_horoscope_stars(
        target_year_stem,
        target_year_branch,
        Scope::Yearly,
        language,
    );
    let (yearly_suiqian12, yearly_jiangqian12) =
        get_yearly12(target_year_branch, astrolabe.config.algorithm);

    let yearly = YearlyItem {
        base: HoroscopeItem {
            index: yearly_index,
            name: translate_horoscope_name(HoroscopeName::Yearly, language).to_string(),
            heavenly_stem: target_year_stem,
            earthly_branch: target_year_branch,
            palace_names: yearly_palace_names,
            mutagen: yearly_mutagen,
            stars: Some(yearly_stars.to_vec()),
        },
        yearly_dec_star: YearlyDecStar {
            jiangqian12: yearly_jiangqian12.to_vec(),
            suiqian12: yearly_suiqian12.to_vec(),
        },
    };

    // ---- 8. 流月 ----
    let leap_addition = if birthday_is_leap && birthday_lunar_day > 15 {
        1
    } else {
        0
    };
    let date_leap_addition = if target_is_leap && target_lunar_day > 15 {
        1
    } else {
        0
    };
    // 出生时辰的地支原始索引 (0=子, 1=丑, ...)
    let birth_time_branch_raw_index = fix_index(astrolabe.time_index as i32, 12) as i32;

    let monthly_index = fix_index(
        yearly_index as i32 - (birthday_lunar_month + leap_addition)
            + birth_time_branch_raw_index
            + (target_lunar_month + date_leap_addition),
        12,
    );
    let monthly_mutagen = astrolabe.config.mutagens_of(target_month_stem).to_vec();
    let monthly_palace_names = get_palace_names(monthly_index).to_vec();
    let monthly_stars = get_horoscope_stars(
        target_month_stem,
        target_month_branch,
        Scope::Monthly,
        language,
    );

    let monthly = HoroscopeItem {
        index: monthly_index,
        name: translate_horoscope_name(HoroscopeName::Monthly, language).to_string(),
        heavenly_stem: target_month_stem,
        earthly_branch: target_month_branch,
        palace_names: monthly_palace_names,
        mutagen: monthly_mutagen,
        stars: Some(monthly_stars.to_vec()),
    };

    // ---- 9. 流日 ----
    let daily_index = fix_index(monthly_index as i32 + target_lunar_day as i32 - 1, 12);
    let daily_mutagen = astrolabe.config.mutagens_of(target_day_stem).to_vec();
    let daily_palace_names = get_palace_names(daily_index).to_vec();
    let daily_stars =
        get_horoscope_stars(target_day_stem, target_day_branch, Scope::Daily, language);

    let daily = HoroscopeItem {
        index: daily_index,
        name: translate_horoscope_name(HoroscopeName::Daily, language).to_string(),
        heavenly_stem: target_day_stem,
        earthly_branch: target_day_branch,
        palace_names: daily_palace_names,
        mutagen: daily_mutagen,
        stars: Some(daily_stars.to_vec()),
    };

    // ---- 10. 流时 ----
    let target_hour_branch_index = fix_index(time_index as i32, 12) as i32;
    let hourly_index = fix_index(daily_index as i32 + target_hour_branch_index, 12);
    let hourly_mutagen = astrolabe.config.mutagens_of(target_time_stem).to_vec();
    let hourly_palace_names = get_palace_names(hourly_index).to_vec();
    let hourly_stars = get_horoscope_stars(
        target_time_stem,
        target_time_branch,
        Scope::Hourly,
        language,
    );

    let hourly = HoroscopeItem {
        index: hourly_index,
        name: translate_horoscope_name(HoroscopeName::Hourly, language).to_string(),
        heavenly_stem: target_time_stem,
        earthly_branch: target_time_branch,
        palace_names: hourly_palace_names,
        mutagen: hourly_mutagen,
        stars: Some(hourly_stars.to_vec()),
    };

    // ---- 11. 农历日期字符串(lunar_rust 的月份中文名对闰月自带「闰」前缀) ----
    let lunar_date_str = format!(
        "{}{}{}",
        target_lunar.get_year_in_chinese(),
        target_lunar.get_month_in_chinese(),
        target_lunar.get_day_in_chinese(),
    );

    Ok(HoroscopeData {
        solar_date: solar_date.to_string(),
        lunar_date: lunar_date_str,
        decadal,
        age,
        yearly,
        monthly,
        daily,
        hourly,
    })
}

// ============================================================
// 辅助函数
// ============================================================

/// 查找大限宫位索引,返回 (宫位索引, 是否童限)。
///
/// 虚岁落在某宫大限区间内取该宫;尚未起运时为童限,
/// 按虚岁依次映射到 [命宫, 财帛, 疾厄, 夫妻, 福德, 官禄]。
fn find_decadal_palace(astrolabe: &Astrolabe, nominal_age: u32) -> (usize, bool) {
    for p in &astrolabe.palaces {
        let (start, end) = p.decadal.range;
        if nominal_age >= start && nominal_age <= end {
            return (p.index, false);
        }
    }

    let childhood_idx = ((nominal_age as usize).saturating_sub(1)) % CHILDHOOD_PALACES.len();
    let target_palace = CHILDHOOD_PALACES[childhood_idx];

    let idx = astrolabe
        .palaces
        .iter()
        .find(|p| p.name == target_palace)
        .map(|p| p.index)
        .unwrap_or(0);
    (idx, true)
}

/// 查找小限宫位索引
///
/// 根据虚岁查找对应的小限宫位。
fn find_age_palace(astrolabe: &Astrolabe, nominal_age: u32) -> usize {
    for p in &astrolabe.palaces {
        if p.ages.contains(&nominal_age) {
            return p.index;
        }
    }
    0
}

// ============================================================
// HoroscopeData 查询方法
// ============================================================

impl HoroscopeItem {
    /// 将名称解析为 Palace 枚举(通过 palace_names 反查)
    fn palace_index_by_name(&self, name: Palace) -> Option<usize> {
        self.palace_names.iter().position(|p| *p == name)
    }
}

impl HoroscopeData {
    /// 获取小限宫位
    pub fn age_palace<'a>(&self, astrolabe: &'a Astrolabe) -> PalaceRef<'a> {
        astrolabe.palace_at(self.age.index)
    }

    /// 根据宫位名称和运限范围获取宫位
    ///
    /// - Origin: 直接从星盘中按宫位名称查找
    /// - 其他: 从该运限的宫位名称列表中查找索引,返回星盘中对应位置的宫位
    pub fn palace<'a>(
        &self,
        name: Palace,
        scope: Scope,
        astrolabe: &'a Astrolabe,
    ) -> Option<PalaceRef<'a>> {
        if scope == Scope::Origin {
            astrolabe.palace(name)
        } else {
            let scope_item = self.scope_item(scope)?;
            let idx = scope_item.palace_index_by_name(name)?;
            Some(astrolabe.palace_at(idx))
        }
    }

    /// 获取指定宫位的三方四正
    pub fn surround_palaces<'a>(
        &self,
        name: Palace,
        scope: Scope,
        astrolabe: &'a Astrolabe,
    ) -> Option<SurroundedPalaces<'a>> {
        let palace = self.palace(name, scope, astrolabe)?;
        astrolabe.surrounded_palaces(palace.index)
    }

    /// 检查指定运限的四化星是否在指定宫位中
    ///
    /// 检查该运限天干的四化对应星耀是否出现在目标宫位的主星或辅星中。
    pub fn has_horoscope_mutagen(
        &self,
        name: Palace,
        scope: Scope,
        mutagen: Mutagen,
        astrolabe: &Astrolabe,
    ) -> bool {
        if scope == Scope::Origin {
            return false;
        }
        let scope_item = match self.scope_item(scope) {
            Some(i) => i,
            None => return false,
        };
        let palace = match self.palace(name, scope, astrolabe) {
            Some(p) => p,
            None => return false,
        };
        let mutagen_index = match mutagen {
            Mutagen::Lu => 0,
            Mutagen::Quan => 1,
            Mutagen::Ke => 2,
            Mutagen::Ji => 3,
        };
        let star_key = scope_item.mutagen[mutagen_index];
        palace
            .major_stars
            .iter()
            .chain(palace.minor_stars.iter())
            .any(|s| s.key == star_key)
    }

    /// 检查大限和流年的流耀是否包含指定星耀
    ///
    /// 合并大限和流年的流耀,检查指定宫位中是否包含所有指定星耀。
    pub fn has_horoscope_stars(
        &self,
        name: Palace,
        scope: Scope,
        stars: &[StarKey],
        astrolabe: &Astrolabe,
    ) -> bool {
        let palace_idx = match self.palace(name, scope, astrolabe) {
            Some(p) => p.index,
            None => return false,
        };
        let all_keys = self.collect_horoscope_star_keys(palace_idx);
        stars.iter().all(|s| all_keys.contains(s))
    }

    /// 检查大限和流年的流耀是否包含指定星耀中的任意一颗
    pub fn has_one_of_horoscope_stars(
        &self,
        name: Palace,
        scope: Scope,
        stars: &[StarKey],
        astrolabe: &Astrolabe,
    ) -> bool {
        let palace_idx = match self.palace(name, scope, astrolabe) {
            Some(p) => p.index,
            None => return false,
        };
        let all_keys = self.collect_horoscope_star_keys(palace_idx);
        stars.iter().any(|s| all_keys.contains(s))
    }

    /// 检查大限和流年的流耀是否不包含指定星耀
    pub fn not_have_horoscope_stars(
        &self,
        name: Palace,
        scope: Scope,
        stars: &[StarKey],
        astrolabe: &Astrolabe,
    ) -> bool {
        let palace_idx = match self.palace(name, scope, astrolabe) {
            Some(p) => p.index,
            None => return false,
        };
        let all_keys = self.collect_horoscope_star_keys(palace_idx);
        stars.iter().all(|s| !all_keys.contains(s))
    }

    /// 收集指定宫位中大限和流年的所有流耀 StarKey
    fn collect_horoscope_star_keys(&self, palace_idx: usize) -> Vec<StarKey> {
        let mut keys = Vec::new();
        if let Some(stars) = self.decadal.stars.as_ref().and_then(|s| s.get(palace_idx)) {
            keys.extend(stars.iter().map(|s| s.key));
        }
        if let Some(stars) = self
            .yearly
            .base
            .stars
            .as_ref()
            .and_then(|s| s.get(palace_idx))
        {
            keys.extend(stars.iter().map(|s| s.key));
        }
        keys
    }

    /// 获取指定运限范围的 HoroscopeItem
    fn scope_item(&self, scope: Scope) -> Option<&HoroscopeItem> {
        match scope {
            Scope::Decadal => Some(&self.decadal),
            Scope::Yearly => Some(&self.yearly.base),
            Scope::Monthly => Some(&self.monthly),
            Scope::Daily => Some(&self.daily),
            Scope::Hourly => Some(&self.hourly),
            _ => None,
        }
    }
}

impl Astrolabe {
    /// 以本命盘为起点计算目标日期的运限,结果持有本盘,输出语言随本盘。
    ///
    /// - `target_date`: 目标阳历日期,"YYYY-M-D"
    /// - `target_time_index`: 目标时辰索引 0-12
    ///
    /// # Errors
    /// 目标日期非法或目标时辰越界时返回 [`IztroError`]。
    pub fn horoscope(
        &self,
        target_date: &str,
        target_time_index: u8,
    ) -> Result<HoroscopeRef<'_>, IztroError> {
        Ok(HoroscopeRef {
            data: get_horoscope(self, target_date, target_time_index, self.language)?,
            astrolabe: self,
        })
    }
}

impl Astrolabe {
    /// 以本命盘为起点计算**此刻**的运限,日期与时辰取本地时钟。
    ///
    /// # Errors
    /// 本地日期落在支持范围(公历 1583-9999)之外时返回 [`IztroError`]。
    pub fn horoscope_now(&self) -> Result<HoroscopeRef<'_>, IztroError> {
        let now = chrono::Local::now();
        let date = now.format("%Y-%-m-%-d").to_string();
        let time_index =
            crate::utils::time_to_index(now.format("%H").to_string().parse().unwrap_or(0));
        self.horoscope(&date, time_index)
    }
}

impl<'a> HoroscopeRef<'a> {
    /// 小限宫位
    pub fn age_palace(&self) -> PalaceRef<'a> {
        self.data.age_palace(self.astrolabe)
    }

    /// 按宫位名称和运限范围取宫位
    pub fn palace(&self, name: Palace, scope: Scope) -> Option<PalaceRef<'a>> {
        self.data.palace(name, scope, self.astrolabe)
    }

    /// 按宫位名称和运限范围取三方四正
    pub fn surround_palaces(&self, name: Palace, scope: Scope) -> Option<SurroundedPalaces<'a>> {
        self.data.surround_palaces(name, scope, self.astrolabe)
    }

    /// 该运限天干的指定四化星是否落在目标宫位(本命盘范围恒为 false)
    pub fn has_horoscope_mutagen(&self, name: Palace, scope: Scope, mutagen: Mutagen) -> bool {
        self.data
            .has_horoscope_mutagen(name, scope, mutagen, self.astrolabe)
    }

    /// 目标宫位的大限与流年流耀是否**全部**包含指定星耀
    pub fn has_horoscope_stars(&self, name: Palace, scope: Scope, stars: &[StarKey]) -> bool {
        self.data
            .has_horoscope_stars(name, scope, stars, self.astrolabe)
    }

    /// 目标宫位的大限与流年流耀是否包含指定星耀中的**任一颗**
    pub fn has_one_of_horoscope_stars(
        &self,
        name: Palace,
        scope: Scope,
        stars: &[StarKey],
    ) -> bool {
        self.data
            .has_one_of_horoscope_stars(name, scope, stars, self.astrolabe)
    }

    /// 目标宫位的大限与流年流耀是否**一颗都不**包含指定星耀
    pub fn not_have_horoscope_stars(&self, name: Palace, scope: Scope, stars: &[StarKey]) -> bool {
        self.data
            .not_have_horoscope_stars(name, scope, stars, self.astrolabe)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::astro::builder::by_solar;

    fn make_astrolabe() -> Astrolabe {
        by_solar(
            "2000-8-16",
            2,
            Gender::Female,
            true,
            Language::ZhCN,
            Config::default(),
        )
        .unwrap()
    }

    #[test]
    fn test_horoscope_holds_astrolabe() {
        let astrolabe = make_astrolabe();
        let h = astrolabe.horoscope("2023-10-15", 4).unwrap();

        // 回引拿到的是同一张盘,输出语言随本盘
        assert_eq!(h.astrolabe().solar_date, astrolabe.solar_date);
        // 解引用后即运限数据本身
        assert_eq!(h.solar_date, "2023-10-15");

        // 免传星盘的查询与显式传盘的结果一致
        let by_data = h
            .data()
            .palace(Palace::Soul, Scope::Decadal, &astrolabe)
            .unwrap();
        assert_eq!(
            h.palace(Palace::Soul, Scope::Decadal).unwrap().index,
            by_data.index
        );
        assert_eq!(h.age_palace().index, h.data().age_palace(&astrolabe).index);
        assert_eq!(
            h.surround_palaces(Palace::Soul, Scope::Yearly)
                .unwrap()
                .target
                .index,
            by_data.astrolabe().palace_at(h.yearly.index).index
        );
        for m in [Mutagen::Lu, Mutagen::Quan, Mutagen::Ke, Mutagen::Ji] {
            assert_eq!(
                h.has_horoscope_mutagen(Palace::Soul, Scope::Decadal, m),
                h.data()
                    .has_horoscope_mutagen(Palace::Soul, Scope::Decadal, m, &astrolabe)
            );
        }
        let stars = [StarKey::Yunkui, StarKey::Yunyue];
        assert_eq!(
            h.has_horoscope_stars(Palace::Soul, Scope::Decadal, &stars),
            h.data()
                .has_horoscope_stars(Palace::Soul, Scope::Decadal, &stars, &astrolabe)
        );
        assert_eq!(
            h.has_one_of_horoscope_stars(Palace::Soul, Scope::Decadal, &stars),
            !h.not_have_horoscope_stars(Palace::Soul, Scope::Decadal, &stars)
                || h.palace(Palace::Soul, Scope::Decadal).is_none()
        );
    }

    #[test]
    fn test_get_horoscope_basic() {
        let astrolabe = make_astrolabe();
        let horoscope = get_horoscope(&astrolabe, "2023-10-15", 4, Language::ZhCN).unwrap();

        // Basic structure checks
        assert_eq!(horoscope.solar_date, "2023-10-15");
        assert!(!horoscope.lunar_date.is_empty());

        // Decadal should have palace names and stars
        assert_eq!(horoscope.decadal.palace_names.len(), 12);
        assert!(horoscope.decadal.stars.is_some());
        let dec_stars = horoscope.decadal.stars.as_ref().unwrap();
        assert_eq!(dec_stars.len(), 12);

        // Yearly should have stars including nianjie
        assert!(horoscope.yearly.stars.is_some());
        let yr_stars = horoscope.yearly.stars.as_ref().unwrap();
        assert_eq!(yr_stars.len(), 12);

        // Monthly, daily, hourly should have stars
        assert!(horoscope.monthly.stars.is_some());
        assert!(horoscope.daily.stars.is_some());
        assert!(horoscope.hourly.stars.is_some());

        // Nominal age should be reasonable
        assert!(horoscope.age.nominal_age > 0);

        // Mutagen should have 4 entries
        assert_eq!(horoscope.decadal.mutagen.len(), 4);
        assert_eq!(horoscope.yearly.mutagen.len(), 4);
        assert_eq!(horoscope.monthly.mutagen.len(), 4);
        assert_eq!(horoscope.daily.mutagen.len(), 4);
        assert_eq!(horoscope.hourly.mutagen.len(), 4);
    }

    #[test]
    fn test_get_horoscope_nominal_age() {
        let astrolabe = make_astrolabe();
        // 2000年出生,2023年查询
        let horoscope = get_horoscope(&astrolabe, "2023-10-15", 4, Language::ZhCN).unwrap();
        // 虚岁 = 目标农历年 - 出生农历年 + 1
        // 2000年出生 → 2023年大约24虚岁
        assert!(horoscope.age.nominal_age >= 23 && horoscope.age.nominal_age <= 25);
    }

    #[test]
    fn test_get_horoscope_stars_decadal() {
        let stars = get_horoscope_stars(
            HeavenlyStem::Jia,
            EarthlyBranch::Yin,
            Scope::Decadal,
            Language::ZhCN,
        );
        // Should place 10 stars across 12 palaces
        let total: usize = stars.iter().map(|v| v.len()).sum();
        assert_eq!(total, 10);
        // All stars should have Decadal scope
        for palace_stars in &stars {
            for s in palace_stars {
                assert_eq!(s.scope, Scope::Decadal);
            }
        }
    }

    #[test]
    fn test_get_horoscope_stars_yearly_has_nianjie() {
        let stars = get_horoscope_stars(
            HeavenlyStem::Jia,
            EarthlyBranch::Yin,
            Scope::Yearly,
            Language::ZhCN,
        );
        // 流耀 10 颗(魁钺昌曲禄羊陀马鸾喜)+ 流年额外的年解 = 11
        let total: usize = stars.iter().map(|v| v.len()).sum();
        assert_eq!(total, 11);
        let has_nianjie = stars
            .iter()
            .flat_map(|v| v.iter())
            .any(|s| s.key == StarKey::Nianjie);
        assert!(has_nianjie);
    }

    #[test]
    fn test_horoscope_palace_query() {
        let astrolabe = make_astrolabe();
        let horoscope = get_horoscope(&astrolabe, "2023-10-15", 4, Language::ZhCN).unwrap();

        // Origin scope should find palace
        let soul = horoscope.palace(Palace::Soul, Scope::Origin, &astrolabe);
        assert!(soul.is_some());
        assert_eq!(soul.unwrap().name, Palace::Soul);

        // Decadal scope should find palace
        let dec_soul = horoscope.palace(Palace::Soul, Scope::Decadal, &astrolabe);
        assert!(dec_soul.is_some());
    }

    #[test]
    fn test_horoscope_age_palace() {
        let astrolabe = make_astrolabe();
        let horoscope = get_horoscope(&astrolabe, "2023-10-15", 4, Language::ZhCN).unwrap();
        let age_palace = horoscope.age_palace(&astrolabe);
        assert!(age_palace.index < 12);
    }

    #[test]
    fn test_horoscope_surround_palaces() {
        let astrolabe = make_astrolabe();
        let horoscope = get_horoscope(&astrolabe, "2023-10-15", 4, Language::ZhCN).unwrap();
        let sp = horoscope.surround_palaces(Palace::Soul, Scope::Origin, &astrolabe);
        assert!(sp.is_some());
        let sp = sp.unwrap();
        assert_eq!(sp.target.name, Palace::Soul);
    }

    #[test]
    fn test_childhood_decadal() {
        // Test with a very young age (birth year = target year)
        let astrolabe = make_astrolabe();
        let horoscope = get_horoscope(&astrolabe, "2000-12-1", 4, Language::ZhCN).unwrap();
        // Should be age 1, which may be in childhood range
        assert!(horoscope.age.nominal_age <= 2);
        // Decadal index should be valid
        assert!(horoscope.decadal.index < 12);
    }

    #[test]
    fn test_has_horoscope_mutagen() {
        let astrolabe = make_astrolabe();
        let horoscope = get_horoscope(&astrolabe, "2023-10-15", 4, Language::ZhCN).unwrap();

        // The decadal's Lu mutagen star should exist in some palace
        let mutagen_star = horoscope.decadal.mutagen[0]; // Lu
        // Find which palace has this star
        let mut found = false;
        for palace_name in &[
            Palace::Soul,
            Palace::Parents,
            Palace::Spirit,
            Palace::Property,
            Palace::Career,
            Palace::Friends,
            Palace::Surface,
            Palace::Health,
            Palace::Wealth,
            Palace::Children,
            Palace::Spouse,
            Palace::Siblings,
        ] {
            if horoscope.has_horoscope_mutagen(
                *palace_name,
                Scope::Decadal,
                Mutagen::Lu,
                &astrolabe,
            ) {
                found = true;
                break;
            }
        }
        // The mutagen star should be found in at least one palace
        assert!(
            found,
            "Lu mutagen star {:?} should be in some palace",
            mutagen_star
        );
    }

    #[test]
    fn test_has_horoscope_stars_and_not() {
        let astrolabe = make_astrolabe();
        let horoscope = get_horoscope(&astrolabe, "2023-10-15", 4, Language::ZhCN).unwrap();

        // Find a palace that has horoscope stars
        let dec_stars = horoscope.decadal.stars.as_ref().unwrap();
        // Find first non-empty palace in decadal stars
        let mut test_palace_idx = None;
        let mut test_star_key = None;
        for (i, stars) in dec_stars.iter().enumerate() {
            if !stars.is_empty() {
                test_palace_idx = Some(i);
                test_star_key = Some(stars[0].key);
                break;
            }
        }

        if let (Some(idx), Some(key)) = (test_palace_idx, test_star_key) {
            let palace_name = astrolabe.palaces[idx].name;
            // Use Origin scope so the palace is looked up by its native name
            assert!(horoscope.has_horoscope_stars(palace_name, Scope::Origin, &[key], &astrolabe));
            // not_have should return false for a star that exists
            assert!(!horoscope.not_have_horoscope_stars(
                palace_name,
                Scope::Origin,
                &[key],
                &astrolabe
            ));
        }
    }
}