# retoor <retoor@molodetz.nl>

import pytest

from devplacepy.database import get_table, init_db
from devplacepy.services import live_view_relay
from devplacepy.services.containers import store
from devplacepy.services.containers.workspace import provision
from tests.conftest import run_async

PROJECT_UID = "relay-ws-project"
OWNER = "relay-ws-owner"
OTHER = "relay-ws-other"


@pytest.fixture(autouse=True)
def _relay_db():
    init_db()
    get_table("projects").insert(
        {
            "uid": PROJECT_UID,
            "user_uid": OWNER,
            "title": "Relay",
            "description": "",
            "slug": "relay-ws",
            "project_type": "software",
            "status": "In Development",
            "platforms": "",
            "is_private": 0,
            "read_only": 0,
            "stars": 0,
            "created_at": "2026-01-01T00:00:00+00:00",
            "deleted_at": None,
            "deleted_by": None,
        }
    )
    yield
    get_table("instances").delete(project_uid=PROJECT_UID)
    get_table("projects").delete(uid=PROJECT_UID)


def _handler(topic: str):
    for pattern, compute, interval in live_view_relay.VIEWS:
        match = pattern.match(topic)
        if match is not None:
            return compute, match, interval
    raise AssertionError(f"no live view for {topic}")


def _workspace(**overrides) -> dict:
    row = {
        "project_uid": PROJECT_UID,
        "name": "ws-relay",
        "status": store.ST_RUNNING,
        "desired_state": store.DESIRED_RUNNING,
        "is_workspace": 1,
        "workspace_owner_uid": OWNER,
        "ports_json": "[]",
    }
    row.update(overrides)
    return store.create_instance(row)


def test_the_workspace_topic_lives_in_the_owner_namespace():
    instance = _workspace()
    compute, match, interval = _handler(f"user.{OWNER}.workspace.{instance['uid']}")
    assert compute is live_view_relay._workspace_detail
    assert interval == 3.0
    payload = run_async(compute(match))
    assert payload["workspace"]["uid"] == instance["uid"]
    assert payload["workspace"]["phase"] == provision.PHASE_STARTING
    assert payload["workspace"]["editor_ready"] is False
    assert payload["editor_url"] == (
        f"/projects/relay-ws/containers/instances/{instance['uid']}/code/"
    )


def test_the_workspace_topic_never_answers_another_owner():
    instance = _workspace()
    compute, match, _interval = _handler(f"user.{OTHER}.workspace.{instance['uid']}")
    assert run_async(compute(match)) is None


def test_the_workspace_topic_ignores_a_plain_container():
    instance = _workspace(is_workspace=0)
    compute, match, _interval = _handler(f"user.{OWNER}.workspace.{instance['uid']}")
    assert run_async(compute(match)) is None


def test_the_workspace_topic_ignores_an_unknown_instance():
    compute, match, _interval = _handler(f"user.{OWNER}.workspace.does-not-exist")
    assert run_async(compute(match)) is None
