import 'constants.dart';
import 'models.dart';
/// 六亲定位 — 三层结构（家内/家外）
/// © 2026 Jason Li. All rights reserved.

class LiuQinLocator {
  static List<LiuQinEntry> locate(BaziChart chart) {
    final dm = chart.dayMaster;
    final table =
        chart.gender == Gender.male ? maleLiuQin[dm]! : femaleLiuQin[dm]!;
    final entries = <LiuQinEntry>[];

    // Collect all visible stems + hidden stems with positions
    final visible = <String, List<String>>{};
    final labels = ['年', '月', '日', '时'];
    for (var i = 0; i < 4; i++) {
      final p = chart.pillars[i];
      visible.putIfAbsent(p.stem, () => []).add('${labels[i]}干');
      for (final (hs, _) in GanZhi.hiddenStems[p.branch]!) {
        visible.putIfAbsent(hs, () => []).add('${labels[i]}支藏');
      }
    }

    // Palace fallback map
    final palaces = {
      '年': '父母宫',
      '月': '兄弟宫',
      '日': '配偶宫',
      '时': '子女宫',
    };

    for (final e in table.entries) {
      final relation = e.key;
      final stem = e.value;
      final god = tenGod(dm, stem);
      final sources = visible[stem];

      if (sources != null && sources.isNotEmpty) {
        entries.add(LiuQinEntry(
          relation: relation,
          stem: stem,
          tenGod: god,
          source: '原局有星: ${sources.join("、")}',
          layer: '家内·第一层',
        ));
      } else {
        // 无星看宫
        String palace;
        if (relation.contains('父') || relation.contains('母')) {
          palace = palaces['年']!;
        } else if (relation.contains('兄') || relation.contains('姐') || relation.contains('妹')) {
          palace = palaces['月']!;
        } else if (relation.contains('妻') ||
            relation.contains('夫') ||
            relation.contains('配偶')) {
          palace = palaces['日']!;
        } else if (relation.contains('子') || relation.contains('女')) {
          palace = palaces['时']!;
        } else {
          palace = '大运流年寻星';
        }
        entries.add(LiuQinEntry(
          relation: relation,
          stem: stem,
          tenGod: god,
          source: '原局无星：藏于时间，大运流年逢之即应期',
          layer: '家内·第一层（潜）',
          palace: palace,
        ));
      }
    }

    // 第二层：大运显化
    for (final dy in chart.daYun.take(3)) {
      for (final e in table.entries) {
        if (dy.stem == e.value) {
          entries.add(LiuQinEntry(
            relation: e.key,
            stem: e.value,
            tenGod: tenGod(dm, e.value),
            source: '大运${dy.text}显化',
            layer: '家内·第二层',
          ));
        }
        for (final (hs, _) in GanZhi.hiddenStems[dy.branch]!) {
          if (hs == e.value) {
            entries.add(LiuQinEntry(
              relation: e.key,
              stem: e.value,
              tenGod: tenGod(dm, e.value),
              source: '大运${dy.text}藏干显化',
              layer: '家内·第二层',
            ));
          }
        }
      }
    }

    // 第三层：流年十神身份（家外）— 用当前公历年示意
    final nowYear = DateTime.now().year;
    final yearIdx = (nowYear - 1984) % 60;
    final i = yearIdx < 0 ? yearIdx + 60 : yearIdx;
    final gz = GanZhi.sixtyJiaZi[i];
    final flowStem = gz[0];
    entries.add(LiuQinEntry(
      relation: '流年$nowYear',
      stem: flowStem,
      tenGod: tenGod(dm, flowStem),
      source: '流年$gz 以十神身份进入',
      layer: '家外·第三层',
    ));

    return entries;
  }
}
