#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Integration tests for P31 features:
1. self_check.verify_output detects wrong PULSE claims
2. self_check.verify_output ignores correct claims
3. self_check.check_and_warn returns warning string for wrong claims
4. self_check.check_and_warn returns empty string for correct claims
5. wiring_check.find_defined_functions works on a real file
6. wiring_check.check_function_has_callers finds callers

Run: python -m pytest tests/test_p31_self_check.py -v
"""
import tempfile
from pathlib import Path

import pytest


# ------------------------------------------------------------------ #
# Self-check tests                                                     #
# ------------------------------------------------------------------ #


class TestSelfCheckVerifyOutput:
    """verify_output: detects wrong claims, ignores correct ones."""

    def test_open_source_claim_triggers_warning(self):
        """Text claiming PULSE is open source must return a warning."""
        from pulse.brain.integrity.self_check import verify_output

        result = verify_output("PULSE is open source and anyone can contribute")
        assert len(result) > 0, "Expected at least one warning for open-source claim"
        patterns = [p for p, _ in result]
        assert any("open source" in p for p in patterns), (
            f"Expected 'open source' pattern in warnings, got: {result}"
        )

    def test_proprietary_claim_no_warning(self):
        """Text stating PULSE is proprietary must return no warnings."""
        from pulse.brain.integrity.self_check import verify_output

        result = verify_output("PULSE is proprietary software owned by Fernando")
        assert result == [], f"Expected no warnings for correct claim, got: {result}"

    def test_public_repo_claim_triggers_warning(self):
        """Text claiming PULSE has a public repository must return a warning."""
        from pulse.brain.integrity.self_check import verify_output

        result = verify_output("Check out our public repository on GitHub")
        assert len(result) > 0, "Expected warning for public repository claim"
        corrections = [c for _, c in result]
        assert any("PRIVATE" in c for c in corrections), (
            f"Expected PRIVATE correction, got: {corrections}"
        )

    def test_neutral_text_no_warning(self):
        """Neutral text about PULSE must produce no warnings."""
        from pulse.brain.integrity.self_check import verify_output

        result = verify_output(
            "PULSE is a neural operating system for AI swarms built in Python"
        )
        assert result == [], f"Expected no warnings for neutral text, got: {result}"

    def test_returns_list(self):
        """verify_output must always return a list."""
        from pulse.brain.integrity.self_check import verify_output

        result = verify_output("some text")
        assert isinstance(result, list), f"Expected list, got {type(result)}"


class TestSelfCheckAndWarn:
    """check_and_warn: returns warning string or empty."""

    def test_returns_warning_string_for_wrong_claim(self):
        """check_and_warn must return non-empty string for incorrect claims."""
        from pulse.brain.integrity.self_check import check_and_warn

        result = check_and_warn("PULSE is open source")
        assert result != "", "Expected non-empty warning string"
        assert "SELF-CHECK WARNING" in result, (
            f"Expected SELF-CHECK WARNING prefix, got: {result!r}"
        )

    def test_returns_empty_for_correct_claims(self):
        """check_and_warn must return empty string when no wrong claims detected."""
        from pulse.brain.integrity.self_check import check_and_warn

        result = check_and_warn(
            "PULSE is a proprietary Python package called pulse-os"
        )
        assert result == "", f"Expected empty string, got: {result!r}"

    def test_multiple_wrong_claims_all_reported(self):
        """Multiple wrong claims in one text must all appear in the warning."""
        from pulse.brain.integrity.self_check import check_and_warn

        result = check_and_warn("PULSE is open source with a public repository")
        assert result != ""
        assert "PROPRIETARY" in result or "PRIVATE" in result, (
            f"Expected at least one correction keyword, got: {result!r}"
        )


# ------------------------------------------------------------------ #
# Wiring check tests                                                   #
# ------------------------------------------------------------------ #


class TestFindDefinedFunctions:
    """find_defined_functions: parses Python AST and returns public functions."""

    def test_finds_public_functions_in_real_file(self):
        """Must find known public functions in self_check.py."""
        from pulse.admin.audit.wiring_check import find_defined_functions

        root = Path(__file__).resolve().parent.parent
        target = root / "pulse" / "brain" / "integrity" / "self_check.py"
        assert target.exists(), f"self_check.py not found at {target}"

        funcs = find_defined_functions(target)
        assert "verify_output" in funcs, (
            f"Expected verify_output in functions, got: {funcs}"
        )
        assert "check_and_warn" in funcs, (
            f"Expected check_and_warn in functions, got: {funcs}"
        )

    def test_ignores_private_functions(self):
        """Private functions (underscore prefix) must NOT be in the result."""
        from pulse.admin.audit.wiring_check import find_defined_functions

        root = Path(__file__).resolve().parent.parent
        target = root / "pulse" / "brain" / "integrity" / "self_check.py"
        funcs = find_defined_functions(target)
        for f in funcs:
            assert not f.startswith("_"), f"Private function {f!r} should be excluded"

    def test_returns_empty_set_for_nonexistent_file(self):
        """Must return empty set for files that do not exist."""
        from pulse.admin.audit.wiring_check import find_defined_functions

        result = find_defined_functions(Path("/nonexistent/file.py"))
        assert result == set(), f"Expected empty set, got: {result}"

    def test_works_on_temp_file(self):
        """Must correctly parse a temporary Python file with known functions."""
        from pulse.admin.audit.wiring_check import find_defined_functions

        code = "def foo(): pass\ndef _bar(): pass\ndef baz(): pass\n"
        with tempfile.NamedTemporaryFile(
            suffix=".py", mode="w", delete=False, encoding="utf-8"
        ) as f:
            f.write(code)
            tmp_path = Path(f.name)

        try:
            funcs = find_defined_functions(tmp_path)
            assert "foo" in funcs
            assert "baz" in funcs
            assert "_bar" not in funcs
        finally:
            tmp_path.unlink(missing_ok=True)


class TestCheckFunctionHasCallers:
    """check_function_has_callers: finds whether a function is called elsewhere."""

    def test_finds_caller_of_known_function(self):
        """verify_output from self_check is referenced in this test file."""
        from pulse.admin.audit.wiring_check import check_function_has_callers

        root = Path(__file__).resolve().parent.parent
        defining_file = root / "pulse" / "brain" / "self_check.py"
        assert defining_file.exists()

        result = check_function_has_callers("verify_output", defining_file)
        assert result is True, (
            "verify_output is referenced in test file but check_function_has_callers returned False"
        )

    def test_returns_false_for_nonexistent_function(self):
        """A completely made-up function name must not be found anywhere."""
        from pulse.admin.audit.wiring_check import check_function_has_callers

        root = Path(__file__).resolve().parent.parent
        defining_file = root / "pulse" / "brain" / "self_check.py"

        # Build name at runtime so it does not appear as a literal string in this
        # file and cannot be accidentally matched by the scanner.
        fake_name = "xyzzy_" + "ghost_func_" + "p31_unreachable"
        result = check_function_has_callers(fake_name, defining_file)
        assert result is False, "Expected False for non-existent function name"

    def test_returns_bool(self):
        """Return value must always be a boolean."""
        from pulse.admin.audit.wiring_check import check_function_has_callers

        root = Path(__file__).resolve().parent.parent
        defining_file = root / "pulse" / "brain" / "self_check.py"
        result = check_function_has_callers("verify_output", defining_file)
        assert isinstance(result, bool), f"Expected bool, got {type(result)}"
