"""
Common pytest fixtures for tests in qualpipe.

This module reuses ctapipe's test infrastructure to avoid duplication.
We use ctapipe's get_dataset_path() for managing test data files, which handles
caching and downloading so test files are shared between ctapipe and qualpipe.
"""

import numpy as np
import pytest
from astropy.table import Table
from astropy.time import Time
from ctapipe.instrument import SubarrayDescription
from ctapipe.utils import get_dataset_path

# Base URL for DPPS test data on minio server
DPPS_TESTDATA_URL = "https://minio-cta.zeuthen.desy.de/dpps-testdata-public/data/"

# ============================================================================
# Sample data fixtures for basic unit tests
# ============================================================================


@pytest.fixture()
def sample_table():
    """
    Create a sample table with time_mono, event_id, and data columns.
    """
    return Table(
        {
            "time": Time(
                [
                    "2020-01-01T00:00:00",
                    "2020-01-01T00:00:01",
                    "2020-01-01T00:00:02",
                    "2020-01-01T00:00:03",
                    "2020-01-01T00:00:04",
                ]
            ),
            "event_id": np.array([0, 1, 2, 3, 4]),
            "data": np.array([0, 1, 2, 3, 4], dtype=float),
        }
    )


@pytest.fixture()
def sample_table_extended():
    """
    Create an extended sample table with more events for testing time windows.
    """
    rng = np.random.default_rng(42)
    n_events = 100
    return Table(
        {
            "time": Time("2020-01-01T00:00:00")
            + np.arange(n_events) * 1.0,  # 1 second per event
            "event_id": np.arange(n_events),
            "data": rng.normal(50, 10, n_events),  # Random data around 50 with std 10
        }
    )


# ============================================================================
# Subarray and instrument fixtures (using ctapipe test data)
# ============================================================================


@pytest.fixture(scope="session")
def test_subarray():
    """
    Subarray description for testing using ctapipe's gamma_test_large.simtel.gz file.
    """
    return SubarrayDescription.read(
        get_dataset_path("gamma_test_large.simtel.gz"),
        focal_length_choice="EQUIVALENT",
    )


# ============================================================================
# DL1 test file fixtures (using DPPS test data)
# ============================================================================


@pytest.fixture(scope="session")
def muon_test_dl1_file():
    """
    DL1 test file with muon events.

    Contains ~10k muon events with telescope-specific parameters for quality metric testing.
    """
    url = DPPS_TESTDATA_URL + "calibpipe-test-data/muon-test-data/"
    filename = "muon-_0deg_0deg_run000008___cta-prod6-2156m-LaPalma-lst-dark-ref-degraded-0.8.h5"
    return get_dataset_path(filename, url=url)


@pytest.fixture(scope="session")
def calibpipe_statsagg_dl1_file():
    """
    Camera-calibration statistics aggregation DL1 test file.

    Contains calibration-related statistics and monitoring data for testing
    TrivialDescriptor.
    """
    url = DPPS_TESTDATA_URL + "calibpipe-test-data/camera-calibration-test-data/"
    filename = "calibpipe_v0.3.0_statsagg_same_chunks.dl1.h5"
    return get_dataset_path(filename, url=url)


@pytest.fixture(scope="session")
def calibpipe_camera_calib_dl1_file():
    """Test file with all camera calibration coefficients and pixel statistics."""
    return get_dataset_path("calibpipe_camcalib_single_chunk_i0.1.0.dl1.h5")


@pytest.fixture(scope="session")
def calibpipe_camera_calib_dl1_obsfile_1():
    """Test file with all camera calibration coefficients and pixel statistics from ACADA-LST integration test."""
    url = DPPS_TESTDATA_URL + "qualpipe-test-data/"
    filename = "TEL001_SDH0000_20251022T230327_SBID0000000002000000076_OBSID0000000002000000232_CALIB_CHUNK000.mon.dl1.h5"
    return get_dataset_path(filename, url=url)


@pytest.fixture(scope="session")
def calibpipe_camera_calib_dl1_obsfile_2():
    """Test file with all camera calibration coefficients and pixel statistics from ACADA-LST integration test."""
    url = DPPS_TESTDATA_URL + "qualpipe-test-data/"
    filename = "TEL001_SDH0000_20251022T235008_SBID0000000002000000078_OBSID0000000002000000239_CALIB_CHUNK000.mon.dl1.h5"
    return get_dataset_path(filename, url=url)
