###############################################################################
# (c) Copyright 2020-2026 CERN for the benefit of the LHCb Collaboration      #
#                                                                             #
# This software is distributed under the terms of the GNU General Public      #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING".   #
#                                                                             #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization  #
# or submit itself to any jurisdiction.                                       #
###############################################################################
from glob import glob
from os.path import basename, dirname, join

import pytest
from click.testing import CliRunner as ClickCliRunner
from typer.testing import CliRunner as TyperCliRunner

from LbAPLocal.cli import legacy_main as main
from LbAPLocal.cli.main import app
from LbAPLocal.log_parsing import LogAnalysis, analyse_log

log_paths = glob(join(dirname(__file__), "data", "example-logs", "*.log"))
assert len(log_paths) > 5


# ---------------------------------------------------------------------------
# Structured API tests
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("log_path", log_paths)
def test_analyse_log_returns_structured_data(log_path):
    """analyse_log() returns a LogAnalysis for every example log."""
    with open(log_path, "rt") as fp:
        log_text = fp.read()

    analysis = analyse_log(log_text)
    assert isinstance(analysis, LogAnalysis)

    if basename(log_path).startswith("good-"):
        assert not analysis.has_fatal_issues
    elif basename(log_path).startswith("error-"):
        assert analysis.has_fatal_issues


@pytest.mark.parametrize("log_path", log_paths)
def test_analyse_log_summaries_consistent(log_path):
    """Message summaries have consistent counts."""
    with open(log_path, "rt") as fp:
        log_text = fp.read()

    analysis = analyse_log(log_text)
    for summary in analysis.summaries:
        shown_count = sum(cnt for _, cnt in summary.messages)
        assert shown_count + summary.suppressed_count == summary.total_count


# ---------------------------------------------------------------------------
# Legacy CLI tests (unchanged behaviour)
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("log_path", log_paths)
def test_parse_logs_legacy(log_path):
    runner = ClickCliRunner()
    result = runner.invoke(main, ["parse-log", log_path])

    if basename(log_path).startswith("good-"):
        assert result.exit_code == 0, result.stdout
    elif basename(log_path).startswith("error-"):
        assert result.exit_code == 1, result.stdout
    else:
        raise NotImplementedError(log_path)


# ---------------------------------------------------------------------------
# Modern CLI tests (lb-ap parse-log)
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("log_path", log_paths)
def test_parse_logs_modern(log_path):
    runner = TyperCliRunner()
    result = runner.invoke(app, ["parse-log", log_path])

    if basename(log_path).startswith("good-"):
        assert result.exit_code == 0, result.stdout
    elif basename(log_path).startswith("error-"):
        assert result.exit_code == 1, result.stdout
    else:
        raise NotImplementedError(log_path)
