import logging
import os
from collections.abc import Sequence
from pathlib import Path

import pydantic

from stable_pydantic.source import (
    ModelEntry,  # noqa: F401 (export even though unused) # type: ignore
    SchemaFilesystem,
)

# Library logging setup. Silent by default, users configure their own handlers
logging.getLogger("stable_pydantic").addHandler(logging.NullHandler())

# Environment variable to control migration mode
MIGRATING_ENV_VAR = "STABLE_PYDANTIC_MIGRATING"


def regenerate_current(
    path: Path | str,
    models: Sequence[type[pydantic.BaseModel]],
):
    """Level 1: Regenerate only the current.py files."""
    fs = SchemaFilesystem.open(path, models)
    fs.update_current()


def update_versioned_schemas(
    path: Path | str,
    models: Sequence[type[pydantic.BaseModel]],
):
    """Level 2: Update schemas with versioning."""
    fs = SchemaFilesystem.open(path, models)
    fs.update_versioned_schemas()


def assert_unchanged_schemas(
    path: Path | str,
    models: Sequence[type[pydantic.BaseModel]],
):
    """Assert that the current schema files match the live models."""
    fs = SchemaFilesystem.open(path, models)
    fs.assert_unchanged_schemas()


def assert_compatible_schemas(
    path: Path | str,
    models: Sequence[type[pydantic.BaseModel]],
    forward: bool = False,
    backward: bool = True,
):
    """Assert that all schema versions are compatible."""
    fs = SchemaFilesystem.open(path, models)
    fs.assert_compatible_schemas(forward=forward, backward=backward)


def is_migrating() -> bool:
    """Check if we are in migration mode (STABLE_PYDANTIC_MIGRATING env var)."""
    return os.environ.get(MIGRATING_ENV_VAR, "").lower() in ("1", "true", "yes")


def _pytest_skip(message: str):
    try:
        import pytest
    except ImportError:
        pass
    else:
        pytest.skip(message)


def skip_if_migrating():
    """Skip the current test if we are in migration mode."""
    if is_migrating():
        _pytest_skip("Skipping because we are in migration mode")


def skip_if_not_migrating():
    """Skip the current test if we are NOT in migration mode."""
    if not is_migrating():
        _pytest_skip("Skipping because we are not in migration mode")
