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

import json
from argparse import Namespace
from pathlib import Path

import pytest

from byteb4rb1e.homeostat.cli.commands import DrinkCommand


DATE = "2026-03-19"


def _args(tmp_path: Path, **overrides: object) -> Namespace:
    defaults = {
        "date": DATE,
        "data_dir": tmp_path / "data",
        "amount_ml": 250,
    }
    defaults.update(overrides)
    return Namespace(**defaults)


class TestDrinkCommand:
    def test_writes_water_intake(self, tmp_path):
        cmd = DrinkCommand()
        rc = cmd.execute(_args(tmp_path))
        assert rc == 0

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

        record = json.loads(path.read_text().strip())
        assert record["source"] == "manual"
        assert record["amount_ml"] == 250
        assert record["date"] == DATE

    def test_appends_multiple_entries(self, tmp_path):
        cmd = DrinkCommand()
        cmd.execute(_args(tmp_path, amount_ml=250))
        cmd.execute(_args(tmp_path, amount_ml=500))

        path = tmp_path / "data" / "water-intake" / f"{DATE}.jsonl"
        lines = path.read_text().strip().splitlines()
        assert len(lines) == 2

        assert json.loads(lines[0])["amount_ml"] == 250
        assert json.loads(lines[1])["amount_ml"] == 500

    def test_fails_with_zero(self, tmp_path):
        cmd = DrinkCommand()
        rc = cmd.execute(_args(tmp_path, amount_ml=0))
        assert rc == 1

    def test_fails_with_negative(self, tmp_path):
        cmd = DrinkCommand()
        rc = cmd.execute(_args(tmp_path, amount_ml=-100))
        assert rc == 1
