"""CLI for Polytropos."""

import textwrap
from pathlib import Path
from typing import cast

from plumbum import cli


class Polytropos(cli.Application):
    """Polytropos - Build backend for Odoo modules."""


@Polytropos.subcommand("init")
class Init(cli.Application):
    """Initialize a new Polytropos module."""

    def main(self, path: str = ".") -> int:
        """Create a new Polytropos module."""
        target = Path(path).resolve()

        if target.is_file():
            print(f"Error: {target} is a file, not a directory")
            return 1

        if not target.exists():
            target.mkdir(parents=True)

        if not target.is_dir():
            print(f"Error: {target} is not a directory")
            return 1

        module_name = target.name
        if not module_name:
            module_name = target.parent.name

        # Convert underscores to hyphens for package name
        package_name = module_name.replace("_", "-")

        pyproject_path = target / "pyproject.toml"

        if pyproject_path.exists():
            print(f"Error: {pyproject_path} already exists")
            return 1

        template = textwrap.dedent(f"""\
            [build-system]
            requires = ["polytropos[build]"]
            build-backend = "polytropos.build"

            [project]
            name = "odoo-addon-{package_name}"
            version = "1.0.0"
            description = "Odoo module: {module_name}"
            requires-python = ">=3.11"
            authors = [
                {{name = "Your Name"}}
            ]
            license = {{text = "LGPL-3"}}
            dependencies = [
                "odoo>=19.0",
            ]

            [project.urls]
            Homepage = "https://github.com/your-org/{module_name}"

            [tool.polytropos]
            default_odoo_release = "19.0"

            # [[tool.polytropos.manifest]]
            # depends = ["base"]
            # Add version-specific overrides:
            # [[tool.polytropos.manifest]]
            # releases = ">=18"
            # application = true
        """)

        pyproject_path.write_text(template)
        print(f"Created {pyproject_path} for module '{module_name}'")

        gitignore_path = target / ".gitignore"
        gitignore_template = textwrap.dedent("""\
            __manifest__.py
            PKG-INFO
            __pycache__/
            dist/
        """)

        gitignore_path.write_text(gitignore_template)
        print(f"Created {gitignore_path}")

        init_path = target / "__init__.py"
        init_path.write_text("")
        print(f"Created {init_path}")
        return 0


if __name__ == "__main__":
    Polytropos.run()


def main() -> int:
    """Entry point for the CLI."""
    _, exit_code = Polytropos.run()
    return cast(int, exit_code)
