#! /usr/bin/python3

import os
import sys
from importlib.metadata import Distribution, DistributionFinder

from sphinx.cmd.build import main


class FixedDistribution(Distribution):
    """A distribution with fixed name and version properties."""

    def __init__(self, *, name, version):
        self._name = name
        self._version = version

    def read_text(self, filename):
        return None

    def locate_file(self, path):
        raise NotImplementedError

    @property
    def name(self):
        return self._name

    @property
    def version(self):
        return self._version


class UninstalledDistributionFinder(DistributionFinder):
    """Find cachelib's metadata despite it not being installed."""

    @staticmethod
    def find_distributions(context=DistributionFinder.Context()):
        if context.name == "cachelib":
            return [
                FixedDistribution(
                    name="cachelib", version=os.environ["DEB_VERSION_UPSTREAM"]
                )
            ]
        else:
            return []


sys.meta_path.append(UninstalledDistributionFinder)

raise SystemExit(main(sys.argv[1:]))
