
import pytest

from cyberbrain26.services.safe_oi import progress, proposals
from cyberbrain26.services.safe_oi.file_tools import _safe_path, list_dir, read_file
from cyberbrain26.services.safe_oi.system_tools import system_status


def test_safe_path_valid():
    p = _safe_path("pyproject.toml")
    assert p.is_file()

def test_safe_path_invalid():
    with pytest.raises(PermissionError):
        _safe_path("/etc/passwd")

def test_read_file_success():
    res = read_file("pyproject.toml")
    assert res["status"] == "success"
    assert "project" in res["content"] or "tool" in res["content"]

def test_list_dir_success():
    res = list_dir(".")
    assert res["status"] == "success"
    assert isinstance(res["entries"], list)

def test_system_status():
    st = system_status()
    assert isinstance(st, dict)

def test_progress_functions():
    job_id = "test-job-123"
    progress.create(job_id)
    progress.set_phase(job_id, "test-phase", 50, "Testing...")
    snap = progress.snapshot(job_id)
    assert snap is not None
    assert snap["percent"] == 50
    progress.finish(job_id, result={"ok": True})
    snap_done = progress.snapshot(job_id)
    assert snap_done["done"] is True

def test_proposals_functions(monkeypatch, tmp_path):
    monkeypatch.setattr(proposals, "PROPOSALS_DIR", tmp_path)
    tmp_path.mkdir(parents=True, exist_ok=True)
    res = proposals.save_proposal("Test Title", "Test Desc", "print(1)")
    assert res["status"] == "success"
    pid = res["proposal_id"]
    prop = proposals.read_proposal(pid)
    assert prop["title"] == "Test Title"
    assert prop["status"] == "pending"
    proposals.update_status(pid, "approved")
    prop_updated = proposals.read_proposal(pid)
    assert prop_updated["status"] == "approved"
