"""Generate Strawberry GraphQL types and resolvers from EntitySchema definitions."""

from __future__ import annotations

from pathlib import Path

from ninja_core.schema.entity import EntitySchema

from .base import build_fields_meta, get_template_env, write_generated_file


def _has_field_type(entity: EntitySchema, *type_names: str) -> bool:
    return any(f.field_type.value in type_names for f in entity.fields)


def generate_gql_type(entity: EntitySchema, output_dir: Path) -> Path:
    """Generate GraphQL type and resolver stubs for a single entity.

    Args:
        entity: The entity schema to generate from.
        output_dir: Directory to write the generated file into.

    Returns:
        Path to the generated file.
    """
    env = get_template_env()
    template = env.get_template("gql_type.py.j2")

    content = template.render(
        entity=entity,
        fields_meta=build_fields_meta(entity),
        has_uuid=_has_field_type(entity, "uuid"),
        has_datetime=_has_field_type(entity, "datetime"),
        has_date=_has_field_type(entity, "date"),
    )

    file_path = output_dir / f"{entity.name.lower()}_gql.py"
    write_generated_file(file_path, content)
    return file_path


def generate_graphql(entities: list[EntitySchema], output_dir: Path) -> list[Path]:
    """Generate GraphQL types and resolvers for all entities.

    Args:
        entities: List of entity schemas.
        output_dir: Base directory for generated GQL files.

    Returns:
        List of paths to generated files.
    """
    gql_dir = output_dir / "_generated" / "graphql"
    paths: list[Path] = []

    init_lines = [
        "# AUTO-GENERATED by ninja-codegen — DO NOT EDIT",
        "",
    ]

    for entity in entities:
        path = generate_gql_type(entity, gql_dir)
        paths.append(path)
        init_lines.append(
            f"from .{entity.name.lower()}_gql import "
            f"{entity.name}Type, {entity.name}Input, "
            f"{entity.name}Query, {entity.name}Mutation"
        )

    if entities:
        init_lines.append("")

    init_path = gql_dir / "__init__.py"
    write_generated_file(init_path, "\n".join(init_lines))
    paths.append(init_path)

    return paths
