from __future__ import annotations

import os
from pathlib import Path

from aicd.tools.session_logs_tool import list_session_logs, read_session_log_tail


def test_list_session_logs_empty_dir(tmp_path: Path) -> None:
    d = tmp_path / "logs"
    d.mkdir()
    r = list_session_logs(d, limit=10)
    assert r["ok"] is True
    assert r["files"] == []


def test_list_and_tail_roundtrip(tmp_path: Path) -> None:
    d = tmp_path / "logs"
    d.mkdir()
    p_a = d / "a.log"
    p_a.write_text("line0\n", encoding="utf-8")
    p2 = d / "b.log"
    p2.write_text("old\n" + "x\n" * 500, encoding="utf-8")
    # FAT/Windows may share coarse mtimes; force a older than b for latest=true
    old = p_a.stat().st_mtime
    os.utime(p_a, (old, old - 60.0))

    lst = list_session_logs(d, limit=5)
    assert lst["ok"] is True
    assert {f["name"] for f in lst["files"]} == {"a.log", "b.log"}

    t = read_session_log_tail(d, latest=True, max_lines=50, max_bytes=8000)
    assert t["ok"] is True
    assert t["path"] == str(p2.resolve())
    assert "x" in t["text"]

    t2 = read_session_log_tail(d, filename="a.log", latest=False, max_lines=10)
    assert t2["ok"] is True
    assert "line0" in t2["text"]

    marked = list_session_logs(d, limit=5, current_process_log=p_a)
    assert marked["ok"] is True
    by_name = {x["name"]: x for x in marked["files"]}
    assert by_name["a.log"]["is_this_process"] is True
    assert by_name["b.log"]["is_this_process"] is False


def test_read_tail_line_contains_and_regex_errors(tmp_path: Path) -> None:
    d = tmp_path / "logs"
    d.mkdir()
    p = d / "one.log"
    p.write_text("alpha ONE\nbeta two\n", encoding="utf-8")
    f = read_session_log_tail(
        d, filename="one.log", line_contains="ONE", max_lines=20, max_bytes=4000
    )
    assert f["ok"] is True
    assert f["filtered_line_count"] == 1
    assert "alpha" in f["text"] and "beta" not in f["text"]

    g = read_session_log_tail(
        d, filename="one.log", line_regex=r"^beta", max_lines=20, max_bytes=4000
    )
    assert g["ok"] is True
    assert "beta" in g["text"] and "alpha" not in g["text"]

    bad = read_session_log_tail(
        d,
        filename="one.log",
        line_contains="a",
        line_regex="x",
        max_lines=20,
        max_bytes=4000,
    )
    assert bad["ok"] is False

    bad_re = read_session_log_tail(
        d, filename="one.log", line_regex="(", max_lines=20, max_bytes=4000
    )
    assert bad_re["ok"] is False


def test_explicit_path_must_stay_under_logs_dir(tmp_path: Path) -> None:
    d = tmp_path / "logs"
    d.mkdir()
    outside = tmp_path / "other.log"
    outside.write_text("x\n", encoding="utf-8")
    r = read_session_log_tail(d, explicit_path=outside, max_lines=10, max_bytes=1000)
    assert r["ok"] is False
