"""Tests for Route Chunk Manager (F12)."""

import numpy as np
import pytest

from gps_denied.core.chunk_manager import RouteChunkManager
from gps_denied.core.graph import FactorGraphOptimizer
from gps_denied.schemas.chunk import ChunkStatus
from gps_denied.schemas.graph import FactorGraphConfig
from gps_denied.schemas.metric import Sim3Transform


@pytest.fixture
def chunk_manager():
    opt = FactorGraphOptimizer(FactorGraphConfig())
    return RouteChunkManager(opt)

def test_create_and_get_chunk(chunk_manager):
    flight_id = "flight123"
    chunk = chunk_manager.create_new_chunk(flight_id, 0)

    assert chunk.is_active is True
    assert chunk.start_frame_id == 0
    assert chunk.flight_id == flight_id

    active = chunk_manager.get_active_chunk(flight_id)
    assert active.chunk_id == chunk.chunk_id

def test_add_frame_to_chunk(chunk_manager):
    flight = "fl2"
    chunk_manager.create_new_chunk(flight, 100)

    assert chunk_manager.add_frame_to_chunk(flight, 101) is True

    active = chunk_manager.get_active_chunk(flight)
    assert 101 in active.frames
    assert len(active.frames) == 2

def test_chunk_merging_logic(chunk_manager):
    flight = "fl3"
    c1 = chunk_manager.create_new_chunk(flight, 0)
    c1_id = c1.chunk_id

    c2 = chunk_manager.create_new_chunk(flight, 50)
    c2_id = c2.chunk_id
    chunk_manager.add_frame_to_chunk(flight, 51)

    # c2 is active now, c1 is inactive
    assert chunk_manager.get_active_chunk(flight).chunk_id == c2_id

    transform = Sim3Transform(translation=np.zeros(3), rotation=np.eye(3), scale=1)

    # merge c2 into c1
    res = chunk_manager.merge_chunks(flight, c2_id, c1_id, transform)

    assert res is True

    # c2 frames moved to c1
    assert 50 in c1.frames
    assert len(c2.frames) == 0
    assert c2.matching_status == ChunkStatus.MERGED
    assert c2.is_active is False
