"""Tests for the TQCE Orchestrator."""

import numpy as np
import pytest

from tqce.network.node import CausalNode
from tqce.engine.orchestrator import TQCEOrchestrator


class TestTQCEOrchestrator:
    def _build_problem(self) -> TQCEOrchestrator:
        np.random.seed(42)
        engine = TQCEOrchestrator("Test Problem")
        net = engine.build_network()
        net.add_node(CausalNode("A", time_coordinate=0.0, state_dim=4))
        net.add_node(CausalNode("B", time_coordinate=1.0, state_dim=4))
        net.add_node(CausalNode("C", time_coordinate=2.0, state_dim=4))
        net.add_causal_edge("A", "B", weight=0.8)
        net.add_causal_edge("B", "C", weight=0.6)
        net.add_retrocausal_edge("C", "A", weight=0.4)
        return engine

    def test_build_network_returns_ctn(self):
        engine = TQCEOrchestrator()
        net = engine.build_network()
        from tqce.network.ctn import CausalTensorNetwork
        assert isinstance(net, CausalTensorNetwork)

    def test_solve_returns_result(self):
        engine = self._build_problem()
        result = engine.solve(n_candidate_timelines=5, verbose=False)
        assert "fixed_point" in result
        assert "summary" in result

    def test_solve_with_tec(self):
        engine = self._build_problem()
        result = engine.solve(
            use_tec=True, n_candidate_timelines=5, verbose=False
        )
        assert "tec" in result

    def test_solve_with_ppgd(self):
        engine = self._build_problem()
        result = engine.solve(use_ppgd=True, verbose=False)
        assert "ppgd" in result

    def test_solve_without_tec_or_ppgd(self):
        engine = self._build_problem()
        result = engine.solve(use_tec=False, use_ppgd=False, verbose=False)
        assert "tec" not in result
        assert "ppgd" not in result

    def test_summary_has_expected_keys(self):
        engine = self._build_problem()
        result = engine.solve(verbose=False)
        summary = result["summary"]
        assert summary["problem"] == "Test Problem"
        assert summary["n_nodes"] == 3
        assert summary["n_causal_edges"] == 2
        assert summary["n_retrocausal_edges"] == 1
        assert summary["has_closed_causal_loops"] is True
