"""Read-only report math, deterministic positive/negative selection and offline safety."""
import json
from pathlib import Path

import numpy as np
import pytest

from pallet import pose_comparison_report as report


def test_paired_counts_rescue_and_regression_are_not_net_success():
    g={'good':np.array([True,True,False,False,True])}
    m={'good':np.array([True,False,True,False,False])}
    assert report.paired_counts(g,m)==dict(both_pass=1,rescued=1,regressed=2,both_fail=1)


def test_error_units_keep_metric_and_unverified_separate():
    arrays=dict(y=np.array([[0,0,1,0],[0,0,1,0]],np.float32),width=np.array([2.,1.]))
    pred=arrays['y'].copy();pred[:,0]=[.02,.1]
    metric=report.errors(pred,arrays,'metric');native=report.errors(pred,arrays,'native_unknown')
    np.testing.assert_allclose(metric['position'],[40,100],rtol=1e-6)
    np.testing.assert_allclose(native['position'],[2,10],rtol=1e-6)
    assert metric['good'].tolist()==native['good'].tolist()==[True,False]


def test_macro_weights_groups_not_targets():
    rows=[dict(group_id='a')]+[dict(group_id='b')]*9
    assert report.macro(np.array([1]+[3]*9),rows)==2


def test_svg_is_finite_equal_scale_and_never_uses_false_camera_projection():
    xyz=np.random.default_rng(4).normal(0,.1,(100,3))+[2,0,.2]
    poses=dict(label=np.array([2.,0.,1.,0.]),geometry=np.array([2.01,.02,1.,0.]),model=np.array([2.005,-.01,1.,0.]))
    for zoom in (True,False):
        svg,info=report.xy_plot(xyz,poses,1.,zoom=zoom)
        assert '<svg' in svg and 'nan' not in svg.lower() and info['axis_scale_equal']
        assert info['unit']==('mm_offset' if zoom else 'm')
        assert info['points_drawn']<=2400


def test_escape_html_and_downloads_are_local_only():
    text=report.table(['<b>header</b>'],[['already escaped']])
    assert '<thead>' in text and '<tbody>' in text
    link=report.download_link('results.json','{"ok":true}','application/json','JSON')
    assert 'data:application/json;base64,' in link and 'https://' not in link
    assert 'class="better"' in report.delta(-1) and 'class="worse"' in report.delta(1)


@pytest.fixture(scope='module')
def frozen_cohort():
    if not (report.ROOT/'final_results.json').exists():pytest.skip('Optional frozen experiment outputs')
    return report.read_cohort('metric','test')


def test_report_reproduces_all_frozen_metrics(frozen_cohort):
    c=frozen_cohort;assert len(c['rows'])==574 and len(c['models'])==14
    assert int(c['geometry']['good'].sum())==542
    assert c['models'][report.PRIMARY]['pair']==dict(both_pass=537,rescued=3,regressed=5,both_fail=29)


def test_case_selection_is_deterministic_unique_and_balanced(frozen_cohort):
    metadata={r['target_key']:r for r in map(json.loads,(report.ROOT/'dataset/features.jsonl').read_text().splitlines())}
    first=report.choose_cases(frozen_cohort,metadata);second=report.choose_cases(frozen_cohort,metadata)
    assert first==second and len(first)==12
    assert len({c['index'] for c in first})==12
    assert {'gain','rescue','regress','tradeoff','stable','failure','fallback','secondary'}=={c['category'] for c in first}
    assert all(frozen_cohort['rows'][c['index']]['split']=='test' for c in first)


def test_template_has_no_remote_assets_or_write_APIs():
    html=(report.ASSETS/'index.html').read_text();js=(report.ASSETS/'report.js').read_text()
    assert 'connect-src \'none\'' in html
    assert 'fetch(' not in js and 'XMLHttpRequest' not in js and 'localStorage' not in js
    assert 'http://' not in html and 'https://' not in html


def test_builder_refuses_existing_output(tmp_path):
    (tmp_path/'user-work.txt').write_text('preserve')
    with pytest.raises(ValueError,match='Output is not empty'):report.build(tmp_path,None)
    assert (tmp_path/'user-work.txt').read_text()=='preserve'
