from __future__ import annotations

import os
import sys

import pytest

SCRIPTS = os.path.join(os.path.dirname(__file__), "..", "scripts")
if SCRIPTS not in sys.path:
    sys.path.insert(0, SCRIPTS)

from marriage_match import build_marriage_match_dossier


def chart(asc, moon, venus, mars, *, saturn=210, sun=120, rahu=300, ketu=120):
    return {
        "ascendant": {"longitude": asc},
        "planets": {
            "Moon": {"longitude": moon}, "Venus": {"longitude": venus},
            "Mars": {"longitude": mars}, "Saturn": {"longitude": saturn},
            "Sun": {"longitude": sun}, "Rahu": {"longitude": rahu}, "Ketu": {"longitude": ketu},
        },
    }


def test_default_profile_separates_mars_kuja_from_papasamya():
    a = chart(0, 30, 60, 180, saturn=180)
    b = chart(90, 120, 150, 270, saturn=270)
    report = build_marriage_match_dossier(a, b)
    assert report["rule_profile"]["id"] == "practitioner_consensus_v1"
    assert report["kuja_mangal_dosha"]["person_a"]["scope"] == "Mars only"
    pressure = report["papasamya"]["person_a"]
    assert {row["planet"] for row in pressure["planet_rows"]} == {"Mars", "Saturn", "Sun", "Rahu", "Ketu"}
    assert "score" not in report["kuja_mangal_dosha"]


def test_kuja_comparison_is_gender_neutral_and_not_numeric_tolerance():
    a = chart(0, 30, 60, 180)
    b = chart(90, 120, 150, 270)
    forward = build_marriage_match_dossier(a, b)["kuja_mangal_dosha"]
    reverse = build_marriage_match_dossier(b, a)["kuja_mangal_dosha"]
    assert forward["gender_asymmetry_used"] is False
    assert forward["outcome"] == reverse["outcome"]
    assert forward["comparison_method"] == "neutral_reference_count"


def test_raman_variant_is_visible_and_first_house_difference_is_explicit():
    # Mars in the first house from each reference frame: default sees it;
    # Raman's selected lineage does not.
    same_sign = chart(0, 0, 0, 0)
    default = build_marriage_match_dossier(same_sign, same_sign)
    raman = build_marriage_match_dossier(same_sign, same_sign, profile_id="raman_muhurtha_v1")
    assert default["kuja_mangal_dosha"]["person_a"]["active_reference_count"] == 3
    assert raman["kuja_mangal_dosha"]["person_a"]["active_reference_count"] == 0
    assert raman["rule_profile"]["id"] == "raman_muhurtha_v1"


def test_bhakoot_and_nadi_exceptions_are_exposed_without_rewriting_raw_score():
    # Moon longitudes both in Ashwini but different padas: same Nadi raw zero,
    # candidate cancellation stays a separately auditable flag.
    a = chart(0, 1, 20, 180)
    b = chart(90, 4, 120, 270)
    report = build_marriage_match_dossier(a, b)
    nadi = report["ashtakoota_36"]["exception_review"]["nadi"]
    assert nadi["raw_score"] == 0
    assert "same_nakshatra_different_pada" in nadi["candidate_cancellations"]


def test_international_core_is_order_independent_and_excludes_caste_point():
    a = chart(0, 30, 60, 180)
    b = chart(90, 120, 150, 270)
    forward = build_marriage_match_dossier(a, b)["ashtakoota_36"]["international_core"]
    reverse = build_marriage_match_dossier(b, a)["ashtakoota_36"]["international_core"]
    assert forward["total_score"] == reverse["total_score"]
    assert forward["scores"] == reverse["scores"]
    assert forward["max_score"] == 35.0
    assert "ValuesOrientation" not in forward["scores"]
    assert "Varna" not in forward["scores"]
    dialogue = build_marriage_match_dossier(a, b)["ashtakoota_36"]["shared_life_dialogue"]
    assert dialogue["status"] == "not_scored"


def test_reported_directional_reproduction_is_order_independent_without_varna():
    # The historical directional calculation yields 10 vs 9 when 45 and 200
    # degrees are swapped because it includes Varna.  The product core omits
    # Varna and averages every included Kuta, so input order is immaterial.
    a = chart(0, 45, 80, 120)
    b = chart(90, 200, 170, 210)
    forward = build_marriage_match_dossier(a, b)["ashtakoota_36"]["international_core"]
    reverse = build_marriage_match_dossier(b, a)["ashtakoota_36"]["international_core"]
    assert forward["total_score"] == reverse["total_score"] == 9.0
    assert forward["scores"] == reverse["scores"]
    assert forward["directionality"]["status"] == "symmetric"


def test_zero_degree_moon_is_a_valid_ashtakoota_input():
    result = build_marriage_match_dossier(chart(0, 0, 20, 180), chart(90, 120, 150, 270))
    assert result["ashtakoota_36"]["status"] == "executed"
    assert result["ashtakoota_36"]["international_core"]["person_a_details"]["moon_sign"] == "Aries"


def test_aries_named_ascendant_is_a_valid_lagna_reference():
    # Aries is sign index 0 and must not be discarded by a boolean fallback.
    person_a = {"ascendant": "Aries", "planets": {"Mars": {"longitude": 120.0}}}
    person_b = {"ascendant": "Taurus", "planets": {"Mars": {"longitude": 240.0}}}
    kuja = build_marriage_match_dossier(person_a, person_b)["kuja_mangal_dosha"]
    lagna_frame = kuja["person_a"]["frames"][0]
    assert lagna_frame["reference"] == "lagna"
    assert lagna_frame["reference_sign"] == "Aries"
    assert lagna_frame["mars_house"] == 5
    assert lagna_frame["status"] == "not_triggered"


def test_moon_only_quick_reference_stays_neutral_and_marks_missing_pressure_layers():
    result = build_marriage_match_dossier(
        {"planets": {"Moon": {"longitude": 0.0}}},
        {"planets": {"Moon": {"longitude": 120.0}}},
    )
    assert result["ashtakoota_36"]["status"] == "executed"
    assert result["ashtakoota_36"]["international_core"]["total_score"] == 18.5
    assert result["kuja_mangal_dosha"]["person_a"]["status"] == "not_available"
    assert result["kuja_mangal_dosha"]["person_b"]["status"] == "not_available"


def test_shared_life_dialogue_is_not_a_score_or_questionnaire_store():
    dialogue = build_marriage_match_dossier(chart(0, 30, 60, 180), chart(90, 120, 150, 270))["ashtakoota_36"]["shared_life_dialogue"]
    assert dialogue["status"] == "not_scored"
    assert dialogue["storage"] == "no_answers_collected"
    assert dialogue["prompts"]


def test_non_romantic_scope_is_rejected():
    with pytest.raises(ValueError, match="romantic/marriage"):
        build_marriage_match_dossier(chart(0, 1, 20, 180), chart(90, 4, 120, 270), relationship_type="business")


def test_api_handler_uses_the_new_product_contract_without_legacy_kuja_score():
    from jyotish_api_server import JyotishAPIHandler

    payload = {
        "person_a": chart(0, 1, 20, 180),
        "person_b": chart(90, 4, 120, 270),
    }
    result = JyotishAPIHandler._compute_marriage_match(None, payload)
    assert result["product"] == "marriage_match_product_v1"
    assert result["kuja_mangal_dosha"]["gender_asymmetry_used"] is False
