#!/usr/bin/env python3

"""Test some core functions."""

from typing import ForwardRef, Literal

import pytest

import ctao_datamodel as dm


def test_ucds_in_astro_fields():
    """See if UCD handling works."""
    dm.AstroField(description="test1", ucd="em.energy")

    with pytest.raises(ValueError, match="Unknown"):
        dm.AstroField(description="test1", ucd="bad_ucd")


def test_fits_keywords():
    """See if FITS keyword handling works."""

    dm.AstroField(fits_keyword="ISOK")

    with pytest.raises(ValueError, match="FITS"):
        dm.AstroField(fits_keyword="THIS_IS_TOO_LONG")


def test_type_to_string():
    """Test type to string conversion."""

    class BasicType:
        pass

    assert dm._core.type_to_string(BasicType) == "BasicType"
    assert dm._core.type_to_string(Literal["1.0"]) == "1.0"
    assert dm._core.type_to_string(float | int) == "float|int"
    assert dm._core.type_to_string(ForwardRef("BasicType")) == "BasicType"
    assert dm._core.type_to_string("bork") == "bork"  # already a string


def test_strflag():
    from enum import auto

    class ExampleStrFlag(dm.StrFlag):
        ONE = auto()
        TWO = auto()
        THREE = auto()

    assert ExampleStrFlag("ONE|TWO") == ExampleStrFlag.ONE | ExampleStrFlag.TWO
    assert str(ExampleStrFlag.THREE | ExampleStrFlag.TWO) == "TWO|THREE"


def test_strflag_pydantic():
    from enum import auto

    from pydantic import BaseModel

    class ExampleStrFlag(dm.StrFlag):
        ONE = auto()
        TWO = auto()
        THREE = auto()

    class ExampleModel(BaseModel):
        flag: ExampleStrFlag

    instance = ExampleModel(flag="ONE|TWO")

    assert instance.model_dump()["flag"] == "ONE|TWO"
