import pytest
import json
from pathlib import Path
from unittest.mock import patch, MagicMock

# --- Phase C Imports ---
from pulse.admin.audit.agent_trust import extract_belief_state
from pulse.daemons.synthesis.swarm.crew_composer import _check_epistemic_conflict, score_crew
from pulse.daemons.consolidation.stages.stage_neocortical_extraction import stage_neocortical_extraction
from pulse.core.brain_db import get_conn

def test_belief_state_extraction():
    """Phase C Item 13: Belief-State Inference."""
    # Mock llm_router.dispatch to return a dummy belief state
    with patch('pulse.core.llm_router.dispatch') as mock_dispatch:
        mock_dispatch.return_value = {"beliefs": ["Values speed over safety", "Prefers FP over OOP", "Uses raw SQL over ORMs"]}
        
        # We need mock sessions to parse.
        with patch('pulse.admin.audit.agent_trust.STATE_DIR', Path('tests/mock_state')):
            (Path('tests/mock_state') / "worker_sessions").mkdir(parents=True, exist_ok=True)
            sess_file = Path('tests/mock_state') / "worker_sessions" / "test_sess.json"
            sess_file.write_text(json.dumps({
                "worker_id": "test_agent", 
                "completed_at": "2026-03-27T00:00:00",
                "events": [{"type": "reasoning", "content": "I should just use raw SQL it is faster."}]
            }), encoding="utf-8")
            
            # Also patch STATE_DIR in the local module space if it was imported locally
            with patch('pulse.admin.audit.agent_trust.STATE_DIR', Path('tests/mock_state')):
                beliefs = extract_belief_state("test_agent")
            
            assert len(beliefs) == 3
            assert "Values speed over safety" in beliefs
            
            # Clean up
            import shutil
            shutil.rmtree('tests/mock_state')

def test_epistemic_crew_composition():
    """Phase C Item 14: Prevent pairing agents with contradictory worldviews."""
    crew = [
        {"model": "claude-test-1"},
        {"model": "gemini-test-2"}
    ]
    tasks = [{"complexity": "high", "domain": "architecture"}] # High complexity required
    
    with patch('pulse.core.brain_utils.STATE_DIR', Path('tests/mock_state_crew')):
        Path('tests/mock_state_crew').mkdir(exist_ok=True)
        trust_file = Path('tests/mock_state_crew') / "agent_trust.json"
        trust_file.write_text(json.dumps({
            "agents": {
                "claude-test-1": {"beliefs": ["Strictly types everything", "Test-driven development"]},
                "gemini-test-2": {"beliefs": ["Moves fast and breaks things", "Skips tests for velocity"]}
            }
        }), encoding="utf-8")
        
        with patch('pulse.core.llm_router.dispatch') as mock_dispatch:
            # Simulate the LLM detecting a conflict
            mock_dispatch.return_value = {"conflict": True, "reason": "Claude values safety, Gemini values velocity."}
            
            warnings = _check_epistemic_conflict(crew, tasks)
            assert len(warnings) == 1
            assert "Epistemic Conflict" in warnings[0]
            
            # Clean up
            import shutil
            shutil.rmtree('tests/mock_state_crew')

def test_neocortical_semantic_extraction():
    """Phase C Item 15: Move highly consolidated facts to Corpus Callosum."""
    result = stage_neocortical_extraction(verbose=False)
    assert isinstance(result, dict)
    assert "facts_extracted" in result

