#!/usr/bin/env python3
"""Generate JSON schemas for plot data from plot configuration models."""

import json
import sys
from pathlib import Path

from pydantic import TypeAdapter

# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from qualpipe_webapp.frontend.page_config import (
    CameraViewConfig,
    Histogram1DConfig,
    ScatterPlotConfig,
)


def build_number_schema() -> dict:
    """Build schema for a number array from typing model."""
    schema = TypeAdapter(list[float]).json_schema()
    schema["description"] = "Array of numeric values"
    return schema


def generate_schema_from_plot_config(plot_config_class) -> dict:
    """Generate a data schema based on what fields are used in a plot config."""
    # Determine which fields are present in the data based on plot type
    if plot_config_class == ScatterPlotConfig:
        fetched_data_props = {
            "x": build_number_schema() | {"description": "X axis values"},
            "y": build_number_schema() | {"description": "Y axis values"},
        }
        required = ["x", "y"]
    elif plot_config_class == CameraViewConfig:
        fetched_data_props = {
            "x": build_number_schema() | {"description": "X pixel values"},
        }
        required = ["x"]
    elif plot_config_class == Histogram1DConfig:
        fetched_data_props = {
            "x": build_number_schema() | {"description": "Histogram bin values"},
        }
        required = ["x"]
    else:
        raise ValueError(f"Unknown plot config: {plot_config_class}")

    return {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
            "fetchedData": {
                "type": "object",
                "properties": fetched_data_props,
                "required": required,
                "additionalProperties": False,
            },
            "fetchedMetadata": {
                "type": "object",
                "additionalProperties": True,
            },
        },
        "required": ["fetchedData"],
        "additionalProperties": False,
    }


def main():
    """Generate all data schemas from plot configuration models."""
    output_dir = Path(__file__).parent.parent / "static"

    configs = {
        "scatterplot": ScatterPlotConfig,
        "cameraview": CameraViewConfig,
        "histogram1d": Histogram1DConfig,
    }

    for plot_type, config_class in configs.items():
        schema = generate_schema_from_plot_config(config_class)
        output_file = output_dir / f"data_schema_{plot_type}.yaml"

        with open(output_file, "w") as f:
            json.dump(schema, f, indent=2)

        print(f"✅ Generated {output_file}")


if __name__ == "__main__":
    main()
