# -*- coding: utf-8 -*-
from pathlib import Path
import ast

ROOT = Path(__file__).parent
SRC = (ROOT / 'heart8772_position.py').read_text(encoding='utf-8')
TREE = ast.parse(SRC)
WANTED = {'estimate_vcal_scale_from_yellow_component', 'origin_from_vcal_a_component', 'safe_overlay_position_for_a_marker'}
NODES = [n for n in TREE.body if isinstance(n, ast.FunctionDef) and n.name in WANTED]
NS = {}
exec(compile(ast.Module(body=NODES, type_ignores=[]), '<heart_helpers>', 'exec'), NS)
estimate = NS['estimate_vcal_scale_from_yellow_component']
origin = NS['origin_from_vcal_a_component']
safe = NS['safe_overlay_position_for_a_marker']


def test_scale_067_080_100():
    assert estimate(20, 20) == (20/30, 20/30)
    assert estimate(24, 24) == (0.8, 0.8)
    assert estimate(30, 30) == (1.0, 1.0)


def test_scaled_origin_recovery():
    ox, oy = 100, 200
    for fill, scale in ((20, 20/30), (24, .8), (30, 1.0)):
        cx = ox + 22 * scale
        cy = oy + 18 * scale
        got = origin(cx, cy, fill, fill)
        assert got is not None
        assert got[0] == ox and got[1] == oy


def test_heart_overlay_is_right_of_a():
    marker = {'role':'tl_a', 'abs_x':103, 'abs_y':202, 'w':20, 'h':20}
    x, y, policy = safe(100, 200, marker, 110, 24, 44, 0, (20, 50, 1800, 1000))
    assert x >= 103 + 20 + 8
    assert policy == 'a_marker_right_gap'
    assert y == 200


def test_source_uses_scaled_origin_and_low_scale_marker():
    assert 'VCAL_MARKER_MIN_SIZE = 15' in SRC
    assert 'ig_ext_visual_calibration_marker_A_center_minus_scaled_client_offset_v149' in SRC
    assert 'safe_overlay_position_for_a_marker' in SRC
    assert 'HEART8772_BUILD_VERSION = "2.3.8.149"' in SRC


if __name__ == '__main__':
    test_scale_067_080_100(); test_scaled_origin_recovery(); test_heart_overlay_is_right_of_a(); test_source_uses_scaled_origin_and_low_scale_marker(); print('OK')
