import hashlib
from datetime import datetime, timedelta
from pathlib import Path

import pytest

from cook import util


def test_evaluate_digest(tmp_wd: Path) -> None:
    fn = tmp_wd / "foo.txt"
    fn.write_text("bar")
    assert util.evaluate_hexdigest(fn) == hashlib.sha1(b"bar").hexdigest()


def test_format_timedelta() -> None:
    assert (
        util.format_timedelta(timedelta(1, 13, 17, 28, 40, 3, 8)) == "57 days, 3:40:13"
    )
    assert util.format_timedelta(timedelta(microseconds=999)) == "0:00:00.000999"


def test_format_datetime() -> None:
    assert (
        util.format_datetime(datetime(2023, 7, 25, 13, 7, 9, 777))
        == "2023-07-25 13:07:09"
    )


def test_dict2args() -> None:
    # Basic string value
    assert util.dict2args(output="file.txt") == ["--output=file.txt"]

    # Boolean True adds flag, False omits it
    assert util.dict2args(verbose=True) == ["--verbose"]
    assert util.dict2args(verbose=False) == []

    # Numeric values
    assert util.dict2args(count=3) == ["--count=3"]

    # Lists/tuples joined with commas
    assert util.dict2args(values=[1, 2, 3]) == ["--values=1,2,3"]
    assert util.dict2args(items=("a", "b")) == ["--items=a,b"]

    # Multiple arguments preserve order (Python 3.7+)
    result = util.dict2args(output="out.txt", verbose=True, count=5)
    assert result == ["--output=out.txt", "--verbose", "--count=5"]

    # Positional arguments come after flags
    result = util.dict2args("input.txt", "output.txt", verbose=True)
    assert result == ["--verbose", "input.txt", "output.txt"]

    # flags parameter for names with dashes or other non-identifier chars
    assert util.dict2args(flags={"dry-run": True}) == ["--dry-run"]
    assert util.dict2args(flags={"num-workers": 4}) == ["--num-workers=4"]

    # flags and kwargs combined (kwargs take precedence)
    result = util.dict2args(flags={"output": "old.txt"}, output="new.txt")
    assert result == ["--output=new.txt"]

    # All together: flags, kwargs, and positional
    result = util.dict2args("file.txt", flags={"dry-run": True}, verbose=True)
    assert result == ["--dry-run", "--verbose", "file.txt"]

    # Empty sequences raise ValueError
    with pytest.raises(ValueError, match="empty sequence"):
        util.dict2args(values=[])
    with pytest.raises(ValueError, match="empty sequence"):
        util.dict2args(items=())
