"""Unit tests for the measure CLI command."""

import json
from argparse import Namespace
from pathlib import Path

import pytest

from byteb4rb1e.homeostat.cli.commands import MeasureCommand


DATE = "2026-03-19"


def _args(tmp_path: Path, **overrides: object) -> Namespace:
    defaults = {
        "date": DATE,
        "data_dir": tmp_path / "data",
        "weight": None,
        "body_fat": None,
        "muscle_mass": None,
        "height": 1.80,
        "chest": None,
        "waist": None,
        "hips": None,
        "bicep": None,
        "thigh": None,
    }
    defaults.update(overrides)
    return Namespace(**defaults)


class TestMeasureCommand:
    def test_writes_body_measurement(self, tmp_path):
        cmd = MeasureCommand()
        rc = cmd.execute(_args(tmp_path, weight=72.5))
        assert rc == 0

        path = tmp_path / "data" / "body-measurement" / f"{DATE}.jsonl"
        assert path.exists()

        record = json.loads(path.read_text().strip())
        assert record["source"] == "manual"
        assert record["weight_kg"] == 72.5
        assert record["bmi"] == round(
            72.5 / (1.80 ** 2), 1
        )

    def test_computes_bmi(self, tmp_path):
        cmd = MeasureCommand()
        cmd.execute(_args(
            tmp_path, weight=80.0, height=2.0
        ))

        path = tmp_path / "data" / "body-measurement" / f"{DATE}.jsonl"
        record = json.loads(path.read_text().strip())
        assert record["bmi"] == 20.0

    def test_circumferences(self, tmp_path):
        cmd = MeasureCommand()
        rc = cmd.execute(_args(
            tmp_path,
            chest=98.0, waist=82.0,
            hips=96.0, bicep=33.0, thigh=55.0,
        ))
        assert rc == 0

        path = tmp_path / "data" / "body-measurement" / f"{DATE}.jsonl"
        record = json.loads(path.read_text().strip())
        assert record["chest_cm"] == 98.0
        assert record["waist_cm"] == 82.0
        assert record["hips_cm"] == 96.0
        assert record["bicep_cm"] == 33.0
        assert record["thigh_cm"] == 55.0

    def test_fails_with_no_input(self, tmp_path):
        cmd = MeasureCommand()
        rc = cmd.execute(_args(tmp_path))
        assert rc == 1

    def test_muscle_mass_only(self, tmp_path):
        cmd = MeasureCommand()
        rc = cmd.execute(_args(
            tmp_path, muscle_mass=56.1
        ))
        assert rc == 0

        path = tmp_path / "data" / "body-measurement" / f"{DATE}.jsonl"
        record = json.loads(path.read_text().strip())
        assert record["muscle_mass_kg"] == 56.1
        assert record["weight_kg"] == 0.0
        assert record["bmi"] == 0.0
