from __future__ import annotations

from pathlib import Path

from aicd.session_log import (
    SessionLogger,
    build_startup_info,
    llm_config_for_log,
    new_session_log_path,
    summarize_tool_call,
    summarize_tool_result,
)


def test_new_session_log_path_pattern(tmp_path: Path) -> None:
    p = new_session_log_path(tmp_path)
    assert p.parent == tmp_path.resolve()
    assert len(p.stem) == 15
    assert p.suffix == ".log"


def test_summarize_fs_read_write() -> None:
    sin = summarize_tool_call("fs_read_file", {"path": "a.txt"})
    assert "a.txt" in sin
    sout = summarize_tool_result(
        "fs_read_file",
        {"ok": True, "path": "/p", "size": 999, "text": "x" * 5000, "truncated": False},
    )
    assert "999" in sout
    assert "x" * 100 not in sout

    win = summarize_tool_call(
        "fs_write_file", {"path": "b.txt", "content": "hello" * 1000}
    )
    assert "content_chars" in win
    assert "hello" not in win


def test_session_logger_write(tmp_path: Path) -> None:
    p = tmp_path / "s.log"
    log = SessionLogger(p)
    log.write_event("a", "C", "op", "in1", "out1")
    log.close()
    text = p.read_text(encoding="utf-8")
    assert "a | C | op | in=in1 | out=out1" in text.replace("\n", " ")


def test_build_startup_info() -> None:
    from aicd.config import LLMConfig

    cfg = LLMConfig(api_key="")
    info = build_startup_info(
        home=Path("/h"),
        session_log_path=Path("/h/logs/x.log"),
        session_id="sid",
        workspace_cwd=Path("/w"),
        cfg_summary=llm_config_for_log(cfg),
        layout={
            "config": Path("/h/c.yaml"),
            "db": Path("/h/d.db"),
        },
    )
    assert info["session_id"] == "sid"
    assert "config_path" in info
