"""Manage Containerfile configuration.

Generate Docker-compatible Containerfile with best practices: Python slim
base, uv package manager, non-root user (appuser), optimized layer caching, and
proper permissions. Compatible with Docker, Podman, and OCI-compliant runtimes.

See Also:
    Containerfile spec: https://github.com/containers/common/blob/main/docs/Containerfile.5.md
"""

import json
from pathlib import Path

from pyrig.rig.configs.base.string_ import StringConfigFile
from pyrig.rig.configs.license import LicenseConfigFile
from pyrig.rig.configs.markdown.readme import ReadmeConfigFile
from pyrig.rig.configs.pyproject import PyprojectConfigFile
from pyrig.rig.tools.package_manager import PackageManager


class ContainerfileConfigFile(StringConfigFile):
    """Manage Containerfile generation.

    Produce production-ready Containerfile with Python slim base, uv package
    manager, non-root user (appuser, UID 1000), optimized layer caching, and
    configurable entrypoint. Compatible with Docker, Podman, and buildah.

    Example:
        >>> ContainerfileConfigFile.I.validate()

    See Also:
        `pyrig.rig.configs.pyproject.PyprojectConfigFile`
        `pyrig.rig.tools.package_manager.PackageManager`
    """

    def filename(self) -> str:
        """Return 'Containerfile'."""
        return "Containerfile"

    def parent_path(self) -> Path:
        """Return project root."""
        return Path()

    def extension(self) -> str:
        """Return empty string (no extension)."""
        return ""

    def extension_separator(self) -> str:
        """Return empty string (no separator)."""
        return ""

    def lines(self) -> list[str]:
        """Return Containerfile build instructions via `layers()`."""
        return self.layers()

    def layers(self) -> list[str]:
        """Generate Containerfile build instructions.

        Builds optimized layer sequence: base image, workdir, uv install,
        dependency copy (for caching), user creation, source copy, dependency
        install, cleanup, entrypoint/command.

        Returns:
            Containerfile instructions (FROM, WORKDIR, COPY, RUN, etc.).

        Note:
            Reads from `pyproject.toml` and may make API calls to resolve the
            Python version.
        """
        latest_python_version = PyprojectConfigFile.I.latest_possible_python_version()
        package_root = PackageManager.I.package_root().as_posix()
        project_name = PackageManager.I.project_name()
        workdir = Path(project_name)
        app_user_name = "appuser"
        entrypoint = json.dumps(list(PackageManager.I.run_args(project_name)))
        readme_path, license_path, pyproject_path, lock_file_path = (
            ReadmeConfigFile.I.path().as_posix(),
            LicenseConfigFile.I.path().as_posix(),
            PyprojectConfigFile.I.path().as_posix(),
            PackageManager.I.lock_file().as_posix(),
        )
        copy_files = f"{readme_path} {license_path} {pyproject_path} {lock_file_path}"
        install_dependencies_no_dev = (
            PackageManager.I.install_dependencies_no_dev_args()
        )
        image_url, image_source_path, image_destination_path = (
            PackageManager.I.container_image()
        )

        return [
            f"FROM python:{latest_python_version}-slim",
            f"WORKDIR /{workdir}",
            f"COPY --from={image_url} {image_source_path} {image_destination_path}",
            f"COPY {copy_files} ./",
            f"RUN useradd -m -u 1000 {app_user_name}",
            f"RUN chown -R {app_user_name}:{app_user_name} .",
            f"USER {app_user_name}",
            f"COPY --chown=appuser:appuser {package_root} {package_root}",
            f"RUN {install_dependencies_no_dev}",
            f"RUN rm {copy_files}",
            f"ENTRYPOINT {entrypoint}",
            "",
        ]
