from datetime import datetime, timedelta, timezone
from pathlib import Path
from mars_bot.sent_log import append_log, count_recent_sends, RATE_LIMIT_PER_HOUR


def test_append_creates_file_and_dir(tmp_path: Path):
    log = tmp_path / "data" / "sent.log"
    append_log(log, "team", "hello world")
    assert log.exists()
    line = log.read_text().strip()
    assert " | team | hello world" in line


def test_append_preview_truncated_to_200(tmp_path: Path):
    log = tmp_path / "sent.log"
    long_text = "x" * 500
    append_log(log, "team", long_text)
    line = log.read_text().strip()
    preview = line.rsplit(" | ", 1)[1]
    assert len(preview) == 200


def test_append_strips_newlines_in_preview(tmp_path: Path):
    log = tmp_path / "sent.log"
    append_log(log, "team", "line1\nline2\nline3")
    line = log.read_text().strip()
    assert "\n" not in line.rsplit(" | ", 1)[1]


def test_count_recent_empty_file(tmp_path: Path):
    log = tmp_path / "sent.log"
    assert count_recent_sends(log) == 0


def test_count_recent_within_window(tmp_path: Path):
    log = tmp_path / "sent.log"
    append_log(log, "team", "a")
    append_log(log, "team", "b")
    append_log(log, "marketing", "c")
    assert count_recent_sends(log) == 3


def test_count_recent_excludes_old_entries(tmp_path: Path):
    log = tmp_path / "sent.log"
    old_ts = (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat()
    fresh_ts = datetime.now(timezone.utc).isoformat()
    log.write_text(
        f"{old_ts} | team | old\n"
        f"{fresh_ts} | team | fresh\n"
    )
    assert count_recent_sends(log) == 1


def test_count_recent_ignores_malformed_lines(tmp_path: Path):
    log = tmp_path / "sent.log"
    fresh_ts = datetime.now(timezone.utc).isoformat()
    log.write_text(f"garbage line\n{fresh_ts} | team | ok\n\n")
    assert count_recent_sends(log) == 1


def test_rate_limit_constant_is_twenty():
    assert RATE_LIMIT_PER_HOUR == 20


def test_count_recent_warns_on_malformed_line(tmp_path: Path, capsys):
    log = tmp_path / "sent.log"
    fresh_ts = datetime.now(timezone.utc).isoformat()
    log.write_text(f"garbage_line\n{fresh_ts} | team | ok\n")
    count = count_recent_sends(log)
    assert count == 1
    err = capsys.readouterr().err
    assert "sent_log" in err
    assert "garbage_line" in err
