#!/usr/bin/env python3
"""Source-bounded Niryaana Shoola Dasha Mahadasha producer."""

from __future__ import annotations

from datetime import datetime, timedelta
from typing import Any
from scripts.dasha_profile_arbitration import attach_profile_arbitration

from scripts.rashi_dasha_explicit_contract import add_calendar_years
from scripts.rashi_dasha_explicit_contract import attach_direct_calendar_antardashas
from scripts.rashi_dasha_explicit_contract import attach_direct_calendar_pratyantardashas


YEAR_DAYS = 365.25636
PROFILE_ID = "goel_nirayana_shoola_v1"
RAMAN_PROFILE_ID = "raman_odd_even_nirayana_v1"
PYJHORA_PROFILE_ID = "pyjhora_2nd_8th_observation_v1"
TOTAL_CYCLE = 108
SIGNS = (
    "Aries",
    "Taurus",
    "Gemini",
    "Cancer",
    "Leo",
    "Virgo",
    "Libra",
    "Scorpio",
    "Sagittarius",
    "Capricorn",
    "Aquarius",
    "Pisces",
)
SIGN_LORDS = {
    0: "Mars", 1: "Venus", 2: "Mercury", 3: "Moon",
    4: "Sun", 5: "Mercury", 6: "Venus", 7: "Mars",
    8: "Jupiter", 9: "Saturn", 10: "Saturn", 11: "Jupiter",
}


def _sign_index(longitude: float) -> int:
    return int(float(longitude) % 360.0 // 30.0)


def _forward_order(start_sign_index: int) -> list[int]:
    return [(int(start_sign_index) + offset) % 12 for offset in range(12)]


def _reverse_order(start_sign_index: int) -> list[int]:
    return [(int(start_sign_index) - offset) % 12 for offset in range(12)]


def resolve_lagna_seventh_tie_break(
    *,
    lagna_sign_index: int,
    planets: dict[str, dict[str, Any]] | None = None,
    planet_strengths: dict[str, float] | None = None,
) -> dict[str, Any]:
    """Resolve a raw Lagna/7th tie from declared chart evidence only."""
    planets = planets if isinstance(planets, dict) else {}
    planet_strengths = planet_strengths if isinstance(planet_strengths, dict) else {}
    lagna = int(lagna_sign_index) % 12
    seventh = (lagna + 6) % 12
    rows = []
    for label, sign in (("lagna", lagna), ("seventh", seventh)):
        occupants = [
            name for name, data in planets.items()
            if isinstance(data, dict) and int(data.get("sign_idx", -1)) % 12 == sign
        ]
        lord = SIGN_LORDS[sign]
        lord_data = planets.get(lord) if isinstance(planets.get(lord), dict) else {}
        degree = lord_data.get("degree_in_sign", lord_data.get("degree"))
        if not isinstance(degree, (int, float)) and isinstance(lord_data.get("lon"), (int, float)):
            degree = float(lord_data["lon"]) % 30.0
        strength = planet_strengths.get(lord)
        rows.append({
            "label": label,
            "sign_index": sign,
            "sign": SIGNS[sign],
            "occupants": occupants,
            "occupant_count": len(occupants),
            "lord": lord,
            "lord_strength": float(strength) if isinstance(strength, (int, float)) else None,
            "lord_degree_in_sign": float(degree) if isinstance(degree, (int, float)) else None,
        })
    comparable = any(
        row["occupant_count"] > 0
        or row["lord_strength"] is not None
        or row["lord_degree_in_sign"] is not None
        for row in rows
    )
    if not comparable:
        return {
            "status": "blocked",
            "reason": "Tie-break requires chart occupants, declared lord strength, or lord degree.",
            "rows": rows,
        }
    keys = [
        (
            row["occupant_count"],
            row["lord_strength"] if row["lord_strength"] is not None else float("-inf"),
            row["lord_degree_in_sign"] if row["lord_degree_in_sign"] is not None else float("-inf"),
        )
        for row in rows
    ]
    if keys[0] == keys[1]:
        return {
            "status": "blocked",
            "reason": "Tie-break evidence remains equal after occupants, lord strength, and lord degree.",
            "rows": rows,
        }
    selected = rows[0] if keys[0] > keys[1] else rows[1]
    return {
        "status": "selected",
        "selected": selected,
        "rows": rows,
        "rule": "occupants_then_sign_lord_strength_then_sign_lord_degree",
        "source_locator": "Public Shoola/Nirayana worked-rule discussions; explicit evidence only.",
    }


def _pyjhora_sign_years(sign_index: int) -> int:
    """Independent transcription of PyJHora's sign-modality duration table."""
    if int(sign_index) in {1, 4, 7, 10}:
        return 8
    if int(sign_index) in {2, 5, 8, 11}:
        return 9
    return 7


def niryaana_shoola_applicability(
    *, ascendant_longitude: float, lagna_strength: float, seventh_strength: float,
    planets: dict[str, dict[str, Any]] | None = None,
    planet_strengths: dict[str, float] | None = None,
) -> dict[str, Any]:
    """Select stronger Lagna/seventh start sign; unresolved ties stay blocked."""
    lagna_sign = _sign_index(ascendant_longitude)
    seventh_sign = (lagna_sign + 6) % 12
    lagna_strength = float(lagna_strength)
    seventh_strength = float(seventh_strength)
    if lagna_strength == seventh_strength:
        tie_break = resolve_lagna_seventh_tie_break(
            lagna_sign_index=lagna_sign,
            planets=planets,
            planet_strengths=planet_strengths,
        )
        if tie_break.get("status") == "selected":
            start = int(tie_break["selected"]["sign_index"])
            return {
                "applicable": True,
                "ascendant_sign_index": lagna_sign,
                "seventh_sign_index": seventh_sign,
                "lagna_strength": lagna_strength,
                "seventh_strength": seventh_strength,
                "starting_sign_index": start,
                "starting_sign": SIGNS[start],
                "rule_family": "goel_niryaana_shoola_stronger_lagna_or_seventh",
                "tie_break": tie_break,
                "reason": "Raw Lagna/7th tie resolved by declared occupants, sign-lord strength, then sign-lord degree.",
            }
        return {
            "applicable": False,
            "execution_status": "blocked",
            "ascendant_sign_index": lagna_sign,
            "seventh_sign_index": seventh_sign,
            "lagna_strength": lagna_strength,
            "seventh_strength": seventh_strength,
            "rule_family": "goel_niryaana_shoola_stronger_lagna_or_seventh",
            "tie_break": tie_break,
            "reason": "Niryaana Shoola start sign requires a declared stronger Lagna or seventh sign; tie-break profile is not closed.",
        }
    start = lagna_sign if lagna_strength > seventh_strength else seventh_sign
    return {
        "applicable": True,
        "ascendant_sign_index": lagna_sign,
        "seventh_sign_index": seventh_sign,
        "lagna_strength": lagna_strength,
        "seventh_strength": seventh_strength,
        "starting_sign_index": start,
        "starting_sign": SIGNS[start],
        "rule_family": "goel_niryaana_shoola_stronger_lagna_or_seventh",
        "reason": "Niryaana Shoola starts from the stronger of Lagna and seventh sign.",
    }


def calculate_niryaana_shoola_dasha(birth_info: dict[str, Any]) -> dict[str, Any]:
    """Return a declared Goel or Raman MD profile; AD/PD stay source-gated."""
    profile_id = birth_info.get("profile_id")
    if profile_id == PYJHORA_PROFILE_ID:
        required = (
            "birth_datetime",
            "ascendant_longitude",
            "second_strength",
            "eighth_strength",
        )
    elif profile_id == RAMAN_PROFILE_ID:
        required = ("birth_datetime", "ascendant_longitude")
    else:
        required = ("birth_datetime", "ascendant_longitude", "lagna_strength", "seventh_strength")
    missing = [field for field in required if birth_info.get(field) is None]
    if missing:
        return {
            "applicable": False,
            "execution_status": "blocked",
            "confidence_status": "blocked",
            "reason": "Missing required input: " + ", ".join(missing),
            "major": [],
        }
    birth = birth_info["birth_datetime"]
    if isinstance(birth, str):
        birth = datetime.fromisoformat(birth)
    lagna_sign = _sign_index(float(birth_info["ascendant_longitude"]))
    if profile_id == PYJHORA_PROFILE_ID:
        lagna_sign = _sign_index(float(birth_info["ascendant_longitude"]))
        second_sign = (lagna_sign + 1) % 12
        eighth_sign = (lagna_sign + 7) % 12
        second_strength = float(birth_info["second_strength"])
        eighth_strength = float(birth_info["eighth_strength"])
        starting_sign = second_sign if second_strength >= eighth_strength else eighth_sign
        direction = "forward" if starting_sign % 2 == 0 else "reverse"
        applicability = {
            "applicable": True,
            "ascendant_sign_index": lagna_sign,
            "second_sign_index": second_sign,
            "eighth_sign_index": eighth_sign,
            "starting_sign_index": starting_sign,
            "starting_sign": SIGNS[starting_sign],
            "direction": direction,
            "second_strength": second_strength,
            "eighth_strength": eighth_strength,
            "rule_family": "pyjhora_niryaana_2nd_8th_modality_profile",
            "reason": (
                "PyJHora behavior profile: stronger 2nd/eighth sign, "
                "odd seed forward and even seed reverse."
            ),
        }
    elif profile_id == RAMAN_PROFILE_ID:
        direction = "forward" if lagna_sign % 2 == 0 else "reverse"
        applicability = {
            "applicable": True,
            "ascendant_sign_index": lagna_sign,
            "starting_sign_index": lagna_sign,
            "starting_sign": SIGNS[lagna_sign],
            "direction": direction,
            "rule_family": "raman_odd_even_lagna_niryaana_shoola",
            "reason": "Raman alternative profile: start from Lagna; parity selects forward or reverse order.",
        }
    else:
        applicability = niryaana_shoola_applicability(
            ascendant_longitude=float(birth_info["ascendant_longitude"]),
            lagna_strength=float(birth_info["lagna_strength"]),
            seventh_strength=float(birth_info["seventh_strength"]),
            planets=birth_info.get("planets"),
            planet_strengths=birth_info.get("planet_strengths"),
        )
    if not applicability["applicable"]:
        return {
            **applicability,
            "profile_id": profile_id or PROFILE_ID,
            "total_cycle": TOTAL_CYCLE,
            "major": [],
            "antardasha": [],
            "pratyantardasha": [],
            "applicable": False,
            "execution_status": "blocked",
            "confidence_status": "blocked",
            "reason": applicability.get("reason") or "Niryaana Shoola selector is unresolved.",
        }
    if profile_id not in {None, PROFILE_ID, RAMAN_PROFILE_ID, PYJHORA_PROFILE_ID}:
        return {
            **applicability,
            "execution_status": "blocked",
            "confidence_status": "blocked",
            "reason": "Unsupported Nirayana Shoola profile_id: " + str(profile_id),
            "major": [],
        }
    if profile_id in {PROFILE_ID, RAMAN_PROFILE_ID, PYJHORA_PROFILE_ID}:
        try:
            rows = []
            cursor = birth
            order = (
                _forward_order(int(applicability["starting_sign_index"]))
                if profile_id == PROFILE_ID
                else (
                    _forward_order(int(applicability["starting_sign_index"]))
                    if applicability["direction"] == "forward"
                    else _reverse_order(int(applicability["starting_sign_index"]))
                )
            )
            for sign_index in order:
                years = (
                    _pyjhora_sign_years(sign_index)
                    if profile_id == PYJHORA_PROFILE_ID
                    else 9
                )
                end = add_calendar_years(cursor, years)
                rows.append({
                    "level": "mahadasha",
                    "sign_index": sign_index,
                    "sign": SIGNS[sign_index],
                    "years": years,
                    "start_date": cursor.isoformat(timespec="seconds"),
                    "end_date": end.isoformat(timespec="seconds"),
                })
                cursor = end
        except ValueError:
            return {
                **applicability,
                "execution_status": "blocked",
                "confidence_status": "blocked",
                "reason": "Calendar-year anniversary cannot be represented for this birth date",
                "major": [],
            }
        payload = {
            **applicability,
            "profile_id": profile_id or PROFILE_ID,
            "execution_status": "executed",
            "confidence_status": "parameter_sensitive",
            "verification_status": "source_bounded_local_profile_replay",
            "period_depth_status": (
                "mahadasha_executed_ad_executed_pd_blocked"
                if profile_id != RAMAN_PROFILE_ID
                else "mahadasha_executed_ad_pd_blocked_source_rule"
            ),
            "total_cycle": TOTAL_CYCLE,
            "duration_basis": "calendar_years",
            "major": rows,
            "reason": (
                (
                    "PyJHora behavior profile replay; source behavior is isolated "
                    "from Goel/Raman lineages and PL9 promotion remains gated."
                    if profile_id == PYJHORA_PROFILE_ID
                    else "Goel NSD profile replay; strength calculation, AD/PD parity, and "
                    "full-reading promotion remain gated."
                )
                if profile_id != RAMAN_PROFILE_ID
                else "Raman odd/even direction profile; AD/PD rule is not admitted by the source packet."
            ),
            "source_locator": (
                "V. P. Goel, Predicting through Jaimini Astrology, pp. 162-168"
                if profile_id != RAMAN_PROFILE_ID
                else "Public Raman alternative summary; source-bounded MD observation only."
            ),
        }
        if profile_id != RAMAN_PROFILE_ID:
            payload["antardasha"] = attach_direct_calendar_antardashas(
                payload["major"], months_per_md_year=9
            )
            payload["pratyantardasha"] = attach_direct_calendar_pratyantardashas(
                payload["major"]
            )
            payload["period_depth_status"] = (
                "mahadasha_antardasha_pratyantardasha_executed_profile_sensitive"
            )
        else:
            payload["antardasha"] = []
            payload["pratyantardasha"] = []
        attach_profile_arbitration(payload, "niryaana_shoola", payload["profile_id"])
        return payload
    year_days = float(birth_info.get("dasha_year_days") or YEAR_DAYS)
    rows = []
    cursor = birth
    for sign_index in _forward_order(int(applicability["starting_sign_index"])):
        end = cursor + timedelta(days=9.0 * year_days)
        rows.append(
            {
                "level": "mahadasha",
                "sign_index": sign_index,
                "sign": SIGNS[sign_index],
                "years": 9,
                "start_date": cursor.isoformat(timespec="seconds"),
                "end_date": end.isoformat(timespec="seconds"),
            }
        )
        cursor = end
    return {
        **applicability,
        "execution_status": "executed",
        "confidence_status": "parameter_sensitive",
        "verification_status": "source_bounded_local_candidate",
        "period_depth_status": "mahadasha_executed_ad_pd_blocked_pending_row_level_replay",
        "total_cycle": TOTAL_CYCLE,
        "dasha_year_days": year_days,
        "major": rows,
        "reason": "Local source-bounded MD calculation; strength source, AD/PD, and runtime wiring remain explicitly gated.",
        "source_locator": "VP Goel / public Jaimini summaries: stronger Lagna-or-seventh start, direct order, 9 years per sign, 108-year cycle.",
    }
