"""
Tests: verify brain boot briefing includes lessons, failures, and patterns.
Task: t_1773842941_009
"""
from __future__ import annotations

import json
import sys
from pathlib import Path
import pytest

PROJECT_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

from pulse.brain.boot.formatters import build_brain_briefing


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _briefing(lessons=None, failures=None, patterns=None, extra=None) -> str:
    data = {
        "lessons": lessons if lessons is not None else [],
        "failures": failures if failures is not None else [],
        "patterns": patterns if patterns is not None else [],
        "anti_patterns": [],
        "decisions": [],
    }
    if extra:
        data.update(extra)
    return build_brain_briefing(data, {})


# ---------------------------------------------------------------------------
# Section presence
# ---------------------------------------------------------------------------

class TestBriefingSections:
    def test_lessons_section_present_when_data_exists(self):
        briefing = _briefing(lessons=["Use filelock for atomic task claiming"])
        assert "## LESSONS LEARNED" in briefing

    def test_failures_section_present_when_data_exists(self):
        briefing = _briefing(failures=["degree column remained 0 due to missing UPDATE"])
        assert "## RECENT FAILURES" in briefing

    def test_patterns_section_present_when_data_exists(self):
        briefing = _briefing(patterns=["Always verify test isolation by checking DB writes"])
        assert "## PROVEN PATTERNS" in briefing

    def test_all_three_sections_present_together(self):
        briefing = _briefing(
            lessons=["Lesson A"],
            failures=["Failure B"],
            patterns=["Pattern C"],
        )
        assert "## LESSONS LEARNED" in briefing
        assert "## RECENT FAILURES" in briefing
        assert "## PROVEN PATTERNS" in briefing

    def test_lessons_content_rendered(self):
        briefing = _briefing(lessons=["Use filelock for task claiming"])
        assert "Use filelock for task claiming" in briefing

    def test_failures_content_rendered(self):
        briefing = _briefing(failures=["degree column remained 0"])
        assert "degree column remained 0" in briefing

    def test_patterns_content_rendered(self):
        briefing = _briefing(patterns=["Query-time degree via JOIN works correctly"])
        assert "Query-time degree via JOIN works correctly" in briefing

    def test_sections_omitted_when_lists_empty(self):
        briefing = _briefing(lessons=[], failures=[], patterns=[])
        assert "## LESSONS LEARNED" not in briefing
        assert "## RECENT FAILURES" not in briefing
        assert "## PROVEN PATTERNS" not in briefing

    def test_briefing_header_always_present(self):
        briefing = _briefing()
        assert "MANDATORY BRAIN BRIEFING" in briefing


# ---------------------------------------------------------------------------
# Integration: load_recent_brain populates all three keys
# ---------------------------------------------------------------------------

class TestLoadRecentBrain:
    def test_load_recent_brain_returns_all_three_keys(self):
        from pulse.brain.boot.loaders import load_recent_brain
        data = load_recent_brain()
        assert "lessons" in data, "load_recent_brain missing 'lessons'"
        assert "failures" in data, "load_recent_brain missing 'failures'"
        assert "patterns" in data, "load_recent_brain missing 'patterns'"

    def test_load_recent_brain_lessons_are_strings(self):
        from pulse.brain.boot.loaders import load_recent_brain
        data = load_recent_brain()
        for item in data["lessons"]:
            assert isinstance(item, str), f"lesson is not a string: {item!r}"

    def test_load_recent_brain_failures_are_strings(self):
        from pulse.brain.boot.loaders import load_recent_brain
        data = load_recent_brain()
        for item in data["failures"]:
            assert isinstance(item, str), f"failure is not a string: {item!r}"

    def test_load_recent_brain_patterns_are_strings(self):
        from pulse.brain.boot.loaders import load_recent_brain
        data = load_recent_brain()
        for item in data["patterns"]:
            assert isinstance(item, str), f"pattern is not a string: {item!r}"

    def test_full_briefing_from_real_brain_has_all_sections(self):
        from pulse.brain.boot.loaders import load_recent_brain
        data = load_recent_brain()
        # Only assert sections that have data (real brain may vary)
        briefing = build_brain_briefing(data, {})
        assert "MANDATORY BRAIN BRIEFING" in briefing
        if data["lessons"]:
            assert "## LESSONS LEARNED" in briefing
        if data["failures"]:
            assert "## RECENT FAILURES" in briefing
        if data["patterns"]:
            assert "## PROVEN PATTERNS" in briefing
