"""Tests for DataProducts model."""

import pytest


def test_bad_product_type():
    """Check that model validation works as expected."""
    import ctao_datamodel.models.dataproducts as dp

    with pytest.raises(ValueError, match="not have division"):
        dp.ProductType(
            level="DL0",
            division="Model",
            association="Telescope",
            type=dp.DataType.CALIBRATION,
        )


def test_product():
    """Test constructing a Product."""

    import uuid

    import ctao_datamodel.models.dataproducts as dp
    from astropy import units as u
    from astropy.coordinates import SkyCoord
    from astropy.time import Time

    example_disclaimer = """
    DISCLAIMER: This data product was generated from simulations. When publishing any result
    using it, please cite the CTAO Science Data challenge...
    """.replace("\n", " ")

    target_dir = SkyCoord.from_name("Crab")
    wobble_offset = 0.9 * u.deg
    pointing_dir = SkyCoord(
        ra=target_dir.ra, dec=target_dir.dec + wobble_offset, frame=target_dir.frame
    )

    epoch = Time(0, format="mjd", scale="utc")  # MJD epoch
    t_start = 5158934318.0  # (Time("2026-05-10 21:18:01.00") - EPOCH).to_value(u.s)
    t_stop = 5158936118.0  # (Time("2026-05-10 21:18:01.00") - EPOCH + 30 * u.min).to_value(u.s)

    dp.Product(
        description="Simulated gamma-like events and IRFs.",
        creation_time=Time.now(),
        curation=dp.Curation(
            release="CTAO-Simulation/DL3-SDC1",
            reference="doi://reference/to/the/sdc/archive",
            license="cc-by-sa",
            license_url="https://creativecommons.org/licenses/by-sa/4.0/",
            copyright="CTAO ERIC",
            rights="public",
        ),
        disclaimer=example_disclaimer,
        data=dp.ProductType(
            level="DL3",
            division="Event",
            association="Subarray",
            type=dp.DataType.OBSERVATION_SIM,
        ),
        instance=dp.InstanceIdentifier(obs_id=1000012345, event_type="hires"),
        model=dp.DataModel(
            name="CTAO-GADF",
            version="v0.3",
            url="https://gamma-astro-data-formats.readthedocs.io/en/v0.3/",
        ),
        contact=dp.Contact(
            name="CTAO HelpDesk", email="help@ctao.org", organization="CTAO"
        ),
        activity=dp.Activity(
            process=dp.ObservatoryProcess.SCIENCE_DATA_CHALLENGE,
            configuration_id="hillas-standard-v1",
            name="sdc-production",
            description="production of SDC data products",
            id=uuid.uuid1(),
            start=Time("2025-11-28 13:45:12.62"),
            software=dp.Software(
                name="SDC_Simulator.py",
                version="v0.1.0-rc1",
                url=(
                    "https://gitlab.cta-observatory.org/cta-science/sdc/sdc-simulations"
                ),
            ),
        ),
        observation=dp.Observation(
            coverage=dp.Coverage(
                time=dp.TimeCoverage(
                    reference=dp.TimeReference(
                        position=dp.TimeRefPos.TOPOCENTER,
                        time_mjd=epoch.mjd,  # MJD reference at 0
                        unit="s",
                        system=dp.TimeSystem.TAI,
                    ),
                    # just some dummy times, here represented in seconds since the
                    t_min=t_start,
                    t_max=t_stop,
                ),
                energy=dp.EnergyCoverage(
                    energy_unit="TeV", energy_min=0.003, energy_max=300.0
                ),
                space=dp.SpaceCoverage(
                    ra=pointing_dir.ra.deg, dec=pointing_dir.dec.deg, field_of_view=6.0
                ),
            ),
        ),
    )


def test_compound_ids():
    """Check ACADADataSource works as object or as a single string."""
    import ctao_datamodel.models.dataproducts as dp

    assert str(dp.ACADADataSource(component="SDH", id=12)) == "SDH012"

    instance = dp.ACADADataSource(component="LIDAR", id=2)
    assert instance.component == "LIDAR"
    assert instance.id == 2


def test_acada_filename():
    import ctao_datamodel.models.dataproducts as dp

    trig = dp.Product(
        description="example metadata testing many cases.",
        creation_time="2025-10-15 18:12:32.2",
        curation=dp.Curation(
            release="CTAO/Dummy",
            reference="doi://reference/to/the/sdc/archive",
            license="cc-by-sa",
            license_url="https://creativecommons.org/licenses/by-sa/4.0/",
            copyright="2026 CTAO ERIC",
            rights="public",
        ),
        disclaimer="This is not realistic metadata",
        data=dp.ProductType(
            level="DL0",
            division="Event",
            association="Subarray",
            type=dp.DataType.TRIGGER,
        ),
        instance=dp.InstanceIdentifier(obs_id=1000012345, subarray_id=5),
        model=dp.DataModel(
            name="CTAO-GADF",
            version="v0.3",
            url="https://gamma-astro-data-formats.readthedocs.io/en/v0.3/",
        ),
        contact=dp.Contact(
            name="CTAO HelpDesk", email="help@ctao.org", organization="CTAO"
        ),
        acquisition=dp.Acquisition(sb_id=12023902),
    )

    event = dp.Product(
        description="example metadata testing many cases.",
        creation_time="2025-10-15 18:12:32.2",
        curation=dp.Curation(
            release="CTAO/Dummy",
            reference="doi://reference/to/the/sdc/archive",
            license="cc-by-sa",
            license_url="https://creativecommons.org/licenses/by-sa/4.0/",
            copyright="2026 CTAO ERIC",
            rights="public",
        ),
        disclaimer="This is not realistic metadata",
        data=dp.ProductType(
            level="DL0",
            division="Event",
            association="Subarray",
            type=dp.DataType.AIRSHOWER,
        ),
        instance=dp.InstanceIdentifier(
            obs_id=1000012345,
            subarray_id=5,
            ae_id=12,
            ae_class="TEL",
        ),
        model=dp.DataModel(
            name="CTAO-GADF",
            version="v0.3",
            url="https://gamma-astro-data-formats.readthedocs.io/en/v0.3/",
        ),
        contact=dp.Contact(
            name="CTAO HelpDesk", email="help@ctao.org", organization="CTAO"
        ),
        acquisition=dp.Acquisition(sb_id=12023902),
    )

    dp.utils.acada_filename(event)
    dp.utils.acada_filename(trig)
