import json
import tempfile
from datetime import datetime
from pathlib import Path
from unittest import mock

import pytest

from autotrainer.behavior import BehaviorAlgorithm, PelletDeviceProtocol, TunnelDeviceProtocol
from autotrainer.training import TrainingProgress, TrainingPhase, TrainingPlan, PredicateContext


@pytest.fixture()
def pellet_device():
    return mock.create_autospec(PelletDeviceProtocol)


@pytest.fixture()
def tunnel_device():
    return mock.create_autospec(TunnelDeviceProtocol)


class TestTrainingPlan:
    """Test TrainingPlan serialization and deserialization"""

    @pytest.fixture
    def test_json_file_path(self):
        """Path to test JSON file"""
        return Path(__file__).parent / "mocks" / "training_plan_serialization.json"

    def test_advance(self, test_json_file_path, pellet_device, tunnel_device):
        plan = TrainingPlan.from_json_file(test_json_file_path)

        BehaviorAlgorithm._no_handler_thread = True

        algorithm = BehaviorAlgorithm()

        plan.behavior_algorithm = algorithm

        assert plan.current_phase.phase_id == "phase-1-uuid-67890"
        assert plan.current_phase.progress.pellets_consumed == 0

        algorithm.start_session()

        algorithm.increase_pellets_consumed(1)

        assert plan.current_phase.progress.pellets_consumed == 1

        algorithm.increase_pellets_consumed(2)

        algorithm.end_session()

        assert plan.current_phase.phase_id == "phase-2-uuid-11111"
        assert plan.current_phase.progress.pellets_consumed == 0
