"""Tests for the vendored AIIQ orchestration bridge."""

import shutil
import tempfile
from pathlib import Path

import pytest

from ares_compression import build_aiiq_runtime, build_aiiq_settings, build_aiiq_task_bridge


@pytest.fixture
def local_tmp_path():
    base_dir = Path.cwd() / ".pytest_tmp"
    base_dir.mkdir(exist_ok=True)
    temp_dir = Path(tempfile.mkdtemp(dir=base_dir))
    try:
        yield temp_dir
    finally:
        shutil.rmtree(temp_dir, ignore_errors=True)


def build_test_settings(tmp_path: Path):
    data_dir = tmp_path / "data"
    artifacts_dir = tmp_path / "artifacts"
    return build_aiiq_settings(
        data_dir=data_dir,
        artifacts_dir=artifacts_dir,
        database_path=data_dir / "tasks.db",
        memory_database_path=data_dir / "memory.db",
        workspaces_dir=data_dir / "workspaces",
        embedding_backend="hash",
        allow_embedding_model_downloads=False,
    )


def test_build_aiiq_settings(local_tmp_path):
    settings = build_test_settings(local_tmp_path)
    assert settings.data_dir == local_tmp_path / "data"
    assert settings.artifacts_dir == local_tmp_path / "artifacts"
    assert settings.embedding_backend == "hash"


def test_build_aiiq_runtime_and_app(local_tmp_path):
    settings = build_test_settings(local_tmp_path)
    runtime = build_aiiq_runtime(settings=settings)
    app = runtime.create_app(run_embedded_worker=False)

    assert runtime.task_service is not None
    assert runtime.task_worker is not None
    assert runtime.openai_compat_service is not None
    assert app is not None


def test_task_bridge_can_submit_task(local_tmp_path):
    settings = build_test_settings(local_tmp_path)
    bridge = build_aiiq_task_bridge(settings=settings)
    repo_path = local_tmp_path / "repo"
    repo_path.mkdir()

    submitted = bridge.submit_task_sync(
        goal="Inspect this workspace and prepare an implementation plan.",
        repo_path=repo_path,
    )

    assert submitted.task_id.startswith("task_")
