from __future__ import annotations

from pathlib import Path

from setuptools import setup
from setuptools.command.develop import develop

try:
    from setuptools.command.editable_wheel import editable_wheel
except ImportError:  # pragma: no cover - setuptools always provides this in dev env
    editable_wheel = None


def exclude_lines_between_markers(
    file_path: str,
    start_marker: str = "<!-- EXCLUDE -->",
    end_marker: str = "<!-- /EXCLUDE -->",
) -> str:
    """
    Reads a file and returns its content with lines between the given markers excluded.
    """
    output_lines = []
    exclude = False
    with Path(file_path).open(encoding="utf-8") as f:
        for line in f:
            if start_marker in line and not exclude:
                exclude = True
                continue
            if end_marker in line and exclude:
                exclude = False
                continue
            if not exclude:
                output_lines.append(line)
    return "".join(output_lines)


readme = exclude_lines_between_markers("README.md")

with Path("src/bluequbit/version.py").open() as f:
    Version = f.read()

Version = Version.rstrip()
Version = Version[15:-1]


def _add_source_only_console_script(distribution) -> None:
    """Register console scripts that should exist only for source installs."""
    entry_points = distribution.entry_points or {}
    console_scripts = list(entry_points.get("console_scripts", []))
    block_image_loader_script = (
        "bluequbit_block_image_loader="
        "bluequbit.library.hierarchical_circuit.block_image_loader_cli:main"
    )
    pps_image_classification_script = (
        "bluequbit_pps_image_classification="
        "bluequbit.library.pps_image_classification.cli:main"
    )
    if block_image_loader_script not in console_scripts:
        console_scripts.append(block_image_loader_script)
    if pps_image_classification_script not in console_scripts:
        console_scripts.append(pps_image_classification_script)
    entry_points["console_scripts"] = console_scripts
    distribution.entry_points = entry_points


class SourceDevelopCommand(develop):
    """Install source-only console scripts during editable/develop installs."""

    def run(self):
        _add_source_only_console_script(self.distribution)
        super().run()


cmdclass = {"develop": SourceDevelopCommand}

if editable_wheel is not None:

    class SourceEditableWheelCommand(editable_wheel):
        """Install source-only console scripts into editable wheels only."""

        def run(self):
            _add_source_only_console_script(self.distribution)
            super().run()

    cmdclass["editable_wheel"] = SourceEditableWheelCommand

setup(
    version=Version,
    long_description=readme,
    long_description_content_type="text/markdown",
    cmdclass=cmdclass,
)
