# Copyright 2026 Dorsal Hub LTD
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import pathlib
import re

from dorsal.common.constants import OPEN_VALIDATION_SCHEMAS_VER
from dorsal.common.exceptions import DorsalError
from dorsal.registry.templates import (
    INIT_TEMPLATE,
    MODEL_CONFIG_TEMPLATE,
    MODEL_TEMPLATE,
    PYPROJECT_TEMPLATE,
    TEST_TEMPLATE,
)
from dorsal.registry.validators import InitResult

logger = logging.getLogger(__name__)


def create_new_annotation_model_project(name: str, target_dir: pathlib.Path | None = None) -> InitResult:
    """
    Create a new Annotation Model project structure on disk:

        my-annotation-model/
        ├── pyproject.toml
        ├── model_config.toml
        ├── README.md
        ├── dorsal_my_annotation_model/
        │   ├── __init__.py
        │   ├── model.py
        │   └── config.py

    Args:
        name: The human-readable name (e.g. "Receipt Scanner").
        target_dir: Optional parent directory. Defaults to CWD.

    Returns:
        InitResult: Metadata about the created project.

    Raises:
        DorsalError: If the directory already exists or writing fails.
    """
    clean_name = re.sub(r"[^a-zA-Z0-9]+", "-", name.lower()).strip("-")
    cwd = target_dir or pathlib.Path.cwd()
    output_dir = cwd / clean_name
    package_name = f"dorsal-{clean_name}"
    module_name = clean_name.replace("-", "_")
    entry_point_name = clean_name.replace("-", "_")
    class_name = "".join(x.title() for x in clean_name.split("-"))

    if output_dir.exists():
        raise DorsalError(f"Directory '{output_dir}' already exists.")

    try:
        output_dir.mkdir(parents=True)
        pkg_dir = output_dir / module_name
        pkg_dir.mkdir()
        tests_dir = output_dir / "tests"
        tests_dir.mkdir()

        (output_dir / "pyproject.toml").write_text(
            PYPROJECT_TEMPLATE.format(
                package_name=package_name,
                human_name=name,
                entry_point_name=entry_point_name,
                module_name=module_name,
            ),
            encoding="utf-8",
        )

        (output_dir / "model_config.toml").write_text(
            MODEL_CONFIG_TEMPLATE.format(class_name=class_name, schema_version=OPEN_VALIDATION_SCHEMAS_VER),
            encoding="utf-8",
        )
        logger.debug(
            f"Wrote: {MODEL_CONFIG_TEMPLATE.format(class_name=class_name, schema_version=OPEN_VALIDATION_SCHEMAS_VER)}"
        )

        (pkg_dir / "model.py").write_text(
            MODEL_TEMPLATE.format(
                class_name=class_name,
                entry_point_name=entry_point_name,
                package_name=package_name,
            ),
            encoding="utf-8",
        )

        (pkg_dir / "__init__.py").write_text(
            INIT_TEMPLATE.format(class_name=class_name),
            encoding="utf-8",
        )

        (tests_dir / "test_model.py").write_text(
            TEST_TEMPLATE.format(module_name=module_name, class_name=class_name, entry_point_name=entry_point_name),
            encoding="utf-8",
        )

        (output_dir / "README.md").write_text(
            f"# {name}\n\nGenerated by Dorsal: https://docs.dorsalhub.com", encoding="utf-8"
        )
        (output_dir / ".gitignore").write_text(
            "\n".join(
                [
                    "build/",
                    "dist/",
                    "*.egg-info/",
                    "__pycache__/",
                    ".pytest_cache/",
                    "\n# Environments",
                    ".env",
                    ".venv",
                    "env/",
                    "venv/",
                    "ENV/",
                    "env.bak/",
                    "venv.bak/",
                    "\n# Dorsal",
                    "dorsal.toml",
                ]
            )
            + "\n",
            encoding="utf-8",
        )

    except OSError as e:
        logger.error(f"Failed to initialize project directory: {e}")
        raise DorsalError(f"Failed to initialize project directory: {e}") from e

    return InitResult(
        path=output_dir,
        package_name=package_name,
        clean_name=clean_name,
    )
