"""JSON Schema generator for form definitions."""

from __future__ import annotations

from corpo.forms.definitions import FormDefinition


def generate_json_schema(form: FormDefinition) -> dict:
    """Generate a JSON Schema from a form definition for programmatic use."""
    properties = {}
    required = []

    for section in form.sections:
        for field in section.fields:
            prop: dict = {"description": field.help or field.label}

            if field.type == "string":
                prop["type"] = "string"
            elif field.type == "choice":
                prop["type"] = "string"
                if field.options:
                    prop["enum"] = field.options
            elif field.type == "integer":
                prop["type"] = "integer"
                prop["minimum"] = 1
            elif field.type == "percentage":
                prop["type"] = "integer"
                prop["minimum"] = 1
                prop["maximum"] = 100

            if field.default is not None:
                prop["default"] = field.default

            if field.validation:
                prop["x-validation"] = field.validation

            properties[field.id] = prop
            if field.required:
                required.append(field.id)

    return {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": form.title,
        "description": form.description,
        "type": "object",
        "properties": properties,
        "required": required,
        "additionalProperties": False,
        "x-form-id": form.form_id,
        "x-form-version": form.version,
    }
