"""Tests for ``mld logs`` command."""

import argparse
from pathlib import Path

import pytest

from mld_sdk.logs_command import _find_log_dir, _list_logs, _tail_lines, cmd_logs


def _make_log_dir(tmp_path: Path) -> Path:
    """Create a .mld/logs/ directory with sample log files."""
    log_dir = tmp_path / ".mld" / "logs"
    log_dir.mkdir(parents=True)
    (log_dir / "plugin-backend.log").write_text(
        "\n".join(f"backend line {i}" for i in range(100))
    )
    (log_dir / "plugin-frontend.log").write_text(
        "\n".join(f"frontend line {i}" for i in range(50))
    )
    (log_dir / "platform-backend.log").write_text(
        "\n".join(f"platform line {i}" for i in range(30))
    )
    return log_dir


class TestFindLogDir:

    def test_finds_existing_dir(self, tmp_path: Path):
        log_dir = tmp_path / ".mld" / "logs"
        log_dir.mkdir(parents=True)
        assert _find_log_dir(tmp_path) == log_dir

    def test_returns_none_when_missing(self, tmp_path: Path):
        assert _find_log_dir(tmp_path) is None


class TestListLogs:

    def test_lists_all_logs(self, tmp_path: Path):
        log_dir = _make_log_dir(tmp_path)
        logs = _list_logs(log_dir)
        assert len(logs) == 3

    def test_filters_by_name(self, tmp_path: Path):
        log_dir = _make_log_dir(tmp_path)
        logs = _list_logs(log_dir, "backend")
        names = [f.stem for f in logs]
        assert "plugin-backend" in names
        assert "platform-backend" in names
        assert "plugin-frontend" not in names

    def test_filters_by_frontend(self, tmp_path: Path):
        log_dir = _make_log_dir(tmp_path)
        logs = _list_logs(log_dir, "frontend")
        assert len(logs) == 1
        assert logs[0].stem == "plugin-frontend"

    def test_no_match_returns_empty(self, tmp_path: Path):
        log_dir = _make_log_dir(tmp_path)
        logs = _list_logs(log_dir, "nonexistent")
        assert logs == []


class TestTailLines:

    def test_returns_last_n_lines(self, tmp_path: Path):
        log_dir = _make_log_dir(tmp_path)
        log_file = log_dir / "plugin-backend.log"
        lines = _tail_lines(log_file, 10)
        assert len(lines) == 10
        assert lines[-1] == "backend line 99"

    def test_returns_all_if_fewer_than_n(self, tmp_path: Path):
        log_dir = _make_log_dir(tmp_path)
        log_file = log_dir / "platform-backend.log"
        lines = _tail_lines(log_file, 100)
        assert len(lines) == 30

    def test_returns_empty_for_missing_file(self, tmp_path: Path):
        lines = _tail_lines(tmp_path / "missing.log", 10)
        assert lines == []


class TestCmdLogs:

    def test_exits_when_no_log_dir(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
        monkeypatch.chdir(tmp_path)
        args = argparse.Namespace(
            process=None, follow=False, lines=50, list_logs=False, clear=False,
        )
        with pytest.raises(SystemExit):
            cmd_logs(args)

    def test_shows_recent_lines(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]):
        _make_log_dir(tmp_path)
        monkeypatch.chdir(tmp_path)
        args = argparse.Namespace(
            process=None, follow=False, lines=5, list_logs=False, clear=False,
        )
        cmd_logs(args)
        output = capsys.readouterr().out
        assert "backend line 99" in output
        assert "frontend line 49" in output

    def test_filters_by_process(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]):
        _make_log_dir(tmp_path)
        monkeypatch.chdir(tmp_path)
        args = argparse.Namespace(
            process="frontend", follow=False, lines=5, list_logs=False, clear=False,
        )
        cmd_logs(args)
        output = capsys.readouterr().out
        assert "frontend line" in output
        assert "backend line" not in output

    def test_list_logs(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]):
        _make_log_dir(tmp_path)
        monkeypatch.chdir(tmp_path)
        args = argparse.Namespace(
            process=None, follow=False, lines=50, list_logs=True, clear=False,
        )
        cmd_logs(args)
        output = capsys.readouterr().out
        assert "plugin-backend" in output
        assert "plugin-frontend" in output
        assert "lines" in output

    def test_clear_logs(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]):
        log_dir = _make_log_dir(tmp_path)
        monkeypatch.chdir(tmp_path)
        args = argparse.Namespace(
            process=None, follow=False, lines=50, list_logs=False, clear=True,
        )
        cmd_logs(args)
        remaining = list(log_dir.glob("*.log"))
        assert remaining == []
        output = capsys.readouterr().out
        assert "Cleared 3" in output


class TestCLIIntegration:

    def test_logs_subcommand_registered(self):
        from mld_sdk.cli import main
        with pytest.raises(SystemExit) as exc_info:
            main(["logs", "--help"])
        assert exc_info.value.code == 0
