from pathlib import Path
from distyctl import constants, types
from distyctl.exceptions import LockFileFormatError


class LockService:
    def __init__(self, target_path: Path):
        self.lock_path = target_path / constants.LOCK_FILE_RELATIVE_PATH

    def lock_version(self, version: types.VersionLiteral):
        """Locks the project to the specified framework version."""
        self.lock_path.write_text(version)

    def is_locked(self):
        return self.lock_path.is_file()

    def get_locked_version(self) -> types.VersionLiteral:
        if not self.is_locked():
            raise RuntimeError("Project is not locked but lock status was queried.")

        version = self.lock_path.read_text()

        if version == "":
            raise LockFileFormatError()

        return version

    def verify_version(self, current_version: types.VersionLiteral):
        """Compares current_version with the locked version and raises a warning or error if they differ."""
        if self.get_locked_version() == current_version:
            raise RuntimeError("Version verification failed")
