from importlib.metadata import PackageNotFoundError

import flask

from abstra_internals.contracts_generated import (
    AbstraLibApiEditorWorkspaceVersionGetResponse,
)
from abstra_internals.controllers.main import MainController
from abstra_internals.usage import editor_usage
from abstra_internals.utils.packages import get_local_package_version


def get_editor_bp(controller: MainController):
    bp = flask.Blueprint("editor_workspace", __name__)

    @bp.get("/")
    @editor_usage
    def _get_workspace():
        return controller.get_workspace().as_dict

    @bp.put("/")
    @editor_usage
    def _update_workspace():
        if not flask.request.json:
            flask.abort(400)
        controller.update_workspace(flask.request.json)
        return controller.get_workspace().as_dict

    @bp.get("/version")
    def _get_abstra_version():
        try:
            version = str(get_local_package_version("abstra"))
        except PackageNotFoundError:
            version = "0.0.0"
        return AbstraLibApiEditorWorkspaceVersionGetResponse(version=version).to_dict()

    return bp
