from copy import deepcopy from datetime import datetime, timedelta, timezone import json from pathlib import Path import subprocess import sys from types import SimpleNamespace import pytest from scripts.kaala_dasha import calculate_kaala_dasha, calculate_kaala_from_events, build_kaala_report def ideal_events(): day = datetime(2000, 1, 1, tzinfo=timezone.utc) return [dict(event=name, datetime_utc=(day+timedelta(days=i,hours=hour)).isoformat()) for i in range(-2,3) for name,hour in [('sunrise',6),('sunset',18)]] def ideal(hour): return calculate_kaala_from_events(epoch=(datetime(2000,1,1,tzinfo=timezone.utc)+timedelta(hours=hour)).isoformat(), solar_events=ideal_events(), solar_event_profile='synthetic_PVR_p2_6am_6pm', year_days=365.25, boundary_policy='start_inclusive') def test_published_5pm_example_all_eighteen_lengths(): result = ideal(17) assert result['seed']['segment'] == 'dusk' assert result['seed']['elapsed_fraction'] == .25 assert result['duration_contract']['cycle_years'] == [30,90] assert [r['years'] for r in result['periods']] == pytest.approx( [2/3,4/3,2,8/3,10/3,4,14/3,16/3,6,2,4,6,8,10,12,14,16,18]) assert result['periods'][-1]['end_age'] == 120 assert result['child_status'] == 'blocked' @pytest.mark.parametrize('hour,segment,fraction', [(0,'nighttime',.5),(4,'dawn',0), (6,'dawn',.5),(8,'daytime',0),(12,'daytime',.5),(16,'dusk',0),(20,'nighttime',0),(23,'nighttime',.375)]) def test_midnight_and_explicit_boundary_ownership(hour,segment,fraction): result = ideal(hour) assert result['seed']['segment'] == segment assert result['seed']['elapsed_fraction'] == fraction if fraction == 0: assert all(r['zero_duration'] for r in result['periods'][:9]) assert result['periods'][9]['start_age'] == 0 def test_unequal_adjacent_nights_use_actual_previous_sunset(): events = [dict(event=n, datetime_utc=t) for n,t in [ ('sunset','1999-12-31T16:00:00Z'),('sunrise','2000-01-01T06:00:00Z'), ('sunset','2000-01-01T18:00:00Z'),('sunrise','2000-01-02T06:00:00Z')]] r = calculate_kaala_from_events(epoch='2000-01-01T05:50:00Z', solar_events=events, solar_event_profile='synthetic_unequal_nights', year_days=365.25, boundary_policy='start_inclusive') assert r['seed']['start_datetime_utc'] == '2000-01-01T03:40:00+00:00' assert r['seed']['end_datetime_utc'] == '2000-01-01T08:00:00+00:00' assert r['seed']['elapsed_fraction'] == .5 @pytest.fixture def request_data(): return dict(epoch='1990-01-01T00:00:00+08:00', latitude=39.9, longitude=116.4, year_days=365.25636, boundary_policy='start_inclusive') def test_real_astronomy_dates_offset_and_router(request_data): # Upstream also routes through specialized_dasha_router / cmd_dasha; ours # serves Kaala through scripts/dasha_registry.compute_dasha instead. r = calculate_kaala_dasha(**request_data) assert r['status'] == 'parameter_sensitive' assert len(r['periods']) == 18 assert r['seed']['segment'] == 'nighttime' assert 0 < r['seed']['elapsed_fraction'] < 1 other = dict(request_data, epoch='1989-12-31T16:00:00Z') assert calculate_kaala_dasha(**other) == r for a,b in zip(r['periods'],r['periods'][1:]): assert a['end_datetime_utc'] == b['start_datetime_utc'] span = datetime.fromisoformat(r['periods'][-1]['end_datetime_utc'])-datetime.fromisoformat(r['epoch_utc']) assert span.total_seconds()/86400 == pytest.approx(120*365.25636) def test_polar_no_six_am_fallback(request_data): r = calculate_kaala_dasha(**dict(request_data, latitude=89, epoch='2000-06-21T12:00:00Z')) assert r['status'] == 'blocked' assert r['periods'] == [] @pytest.mark.parametrize('key,value', [('epoch','2000-01-01'), ('latitude',float('nan')), ('longitude',181), ('year_days',True), ('year_days',0), ('boundary_policy','guess')]) def test_invalid(request_data,key,value): with pytest.raises(ValueError): calculate_kaala_dasha(**dict(request_data,**{key:value})) def test_report_and_portable_cli(request_data,tmp_path): report = build_kaala_report(request_data) assert report['customer_export_admitted'] is False assert 'nighttime' in report['exports']['markdown'] independent = deepcopy(report['exports']['ai_evidence_bundle']) report['evidence_appendix'][0]['result']['periods'].clear() assert report['exports']['ai_evidence_bundle'] == independent path = tmp_path/'input.json' path.write_text(json.dumps(request_data)) module = Path(__file__).resolve().parents[1]/'scripts/kaala_dasha.py' run = subprocess.run([sys.executable,str(module),'--request',str(path)], cwd=tmp_path, capture_output=True,text=True,check=True) assert json.loads(run.stdout)['exports']['ai_evidence_bundle'] == independent def test_malformed_solar_timeline(): events = ideal_events() events[1]['datetime_utc'] = events[0]['datetime_utc'] with pytest.raises(ValueError,match='strictly increase'): calculate_kaala_from_events(epoch='2000-01-01T12:00:00Z', solar_events=events, solar_event_profile='bad',year_days=365.25,boundary_policy='start_inclusive')