# TODO: This doesn't run, because it can't find the tools module.
from pathlib import Path
from typing import Any

import requests
from datamodel_code_generator import DataModelType, InputFileType, LiteralType, generate

from seedcase_sprout.internals import _write_json


def get_schema(path: Path) -> Any:
    """Downloads, preprocesses and extracts dataclasses from the Data Package schema."""
    url = "https://datapackage.org/profiles/2.0/datapackage.json"
    response = requests.get(url, timeout=5)
    response.raise_for_status()
    schema = response.json()

    # edit the schema to simplify the generated class structure
    resource_items = schema["properties"]["resources"]["items"]
    del resource_items["oneOf"][0]
    table_schema_properties = resource_items["properties"]["schema"]["properties"]
    del table_schema_properties["fields"]
    table_schema_fkey_items = table_schema_properties["foreignKeys"]["items"]
    table_schema_fkey_items["properties"] = table_schema_fkey_items["oneOf"][0][
        "properties"
    ]
    del table_schema_fkey_items["oneOf"]

    _write_json(schema, path)
    return schema


def generate_dataclasses(path: Path) -> None:
    """Generates dataclasses from the Data Package schema."""
    output_path = Path("tools/generated_properties.py")

    schema = Path(path).read_text()
    return generate(
        schema,
        input_filename=str(path),
        input_file_type=InputFileType.JsonSchema,
        output_model_type=DataModelType.DataclassesDataclass,
        output=output_path,
        custom_template_dir=Path("tools"),
        custom_formatters=["tools.custom_formatters"],
        custom_file_header="# ruff: noqa\n# NOTE: This content was autogenerated, no need to edit it.",  # noqa
        enum_field_as_literal=LiteralType.All,
        use_one_literal_as_default=True,
        use_standard_collections=True,
        use_title_as_name=True,
        use_union_operator=True,
        snake_case_field=True,
        special_field_name_prefix="ignore",
        use_field_description=True,
        use_schema_description=True,
        use_double_quotes=True,
        reuse_model=True,
        force_optional_for_required_fields=True,
    )


if __name__ == "__main__":
    path = Path("tools/schema.json")
    schema = get_schema(path)
    generate_dataclasses(path)
    path.unlink(missing_ok=True)
