#!/usr/bin/env python3
"""
Generate Pydantic models from Late API OpenAPI specification.

This script uses datamodel-code-generator to create type-safe models
from the OpenAPI spec. Generated models are placed in src/late/models/_generated/
and should NOT be edited manually.

Usage:
    python scripts/generate_models.py
    # or
    uv run python scripts/generate_models.py
"""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path


def main() -> int:
    """Generate models from OpenAPI spec."""
    # Paths
    project_root = Path(__file__).parent.parent
    openapi_spec = project_root / "openapi.yaml"
    output_dir = project_root / "src" / "late" / "models" / "_generated"

    # Validate OpenAPI spec exists (should be fetched first)
    if not openapi_spec.exists():
        print(f"Error: OpenAPI spec not found at {openapi_spec}")
        print("Run 'curl -o openapi.yaml https://getlate.dev/openapi.yaml' first")
        return 1

    # Create output directory
    output_dir.mkdir(parents=True, exist_ok=True)
    output_file = output_dir / "models.py"

    # Run datamodel-code-generator
    cmd = [
        sys.executable,
        "-m",
        "datamodel_code_generator",
        "--input",
        str(openapi_spec),
        "--output",
        str(output_file),
        "--output-model-type",
        "pydantic_v2.BaseModel",
        "--input-file-type",
        "openapi",
        "--use-double-quotes",
        "--target-python-version",
        "3.10",
        "--use-annotated",
        "--field-constraints",
        "--use-field-description",
        "--capitalise-enum-members",
        "--use-default-kwarg",
        "--collapse-root-models",
        "--use-union-operator",
        "--strict-nullable",
        "--use-schema-description",
        "--field-extra-keys-without-x-prefix",
        "deprecated",
    ]

    print(f"Generating models from: {openapi_spec}")
    print(f"Output directory: {output_dir}")
    print()

    try:
        result = subprocess.run(cmd, check=True, capture_output=True, text=True)
        print(result.stdout)
        if result.stderr:
            print(result.stderr)
    except subprocess.CalledProcessError as e:
        print(f"Error generating models: {e}")
        print(f"stdout: {e.stdout}")
        print(f"stderr: {e.stderr}")
        return 1
    except FileNotFoundError:
        print("Error: datamodel-code-generator not found.")
        print("Install it with: pip install datamodel-code-generator")
        return 1

    # Create __init__.py to export all models
    init_file = output_dir / "__init__.py"
    init_content = '''"""
Auto-generated Pydantic models from Late API OpenAPI specification.

DO NOT EDIT THIS FILE MANUALLY.
Run `python scripts/generate_models.py` to regenerate.
"""

from __future__ import annotations

# Re-export all generated models
from .models import *  # noqa: F401, F403
'''
    init_file.write_text(init_content)

    print()
    print("Models generated successfully!")
    print(f"Output: {output_dir}")
    print()
    print("Note: These are base models. Use the curated models in")
    print("src/late/models/ for the public API.")

    return 0


if __name__ == "__main__":
    sys.exit(main())
