#!/usr/bin/env python3
import json
import tempfile
from pathlib import Path
import sys

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))

import cb26_agent_runtime as rt

def test_policy():
    assert rt.policy("pwd")["allowed"] is True
    assert rt.policy("rm /tmp/x")["approval"] is True
    assert rt.policy("echo ok | cat")["approval"] is True

def test_store():
    with tempfile.TemporaryDirectory() as td:
        db = Path(td) / "agent.db"
        store = rt.Store(db)
        run = {
            "run_id": "test-run", "thread_id": "test-thread",
            "status": rt.STATUS_RUNNING, "model": "test-model", "mode": "SAFE",
            "step": 0, "failure_count": 0, "created_at": rt.now_iso(),
            "state": {"messages": [{"role": "system", "content": "test"}],
                      "last_tool_fingerprints": [], "pending_approval_id": None},
        }
        store.save_run(run)
        loaded = store.load_run("test-run")
        assert loaded and loaded["thread_id"] == "test-thread"

def test_chat_endpoint():
    import httpx
    try:
        resp = httpx.post("http://127.0.0.1:7682/chat", json={
            "message": "Ahoj",
            "model": "groq-gpt-oss-120b",
            "mode": "SAFE",
            "confirm_full": False
        }, timeout=15)
        assert resp.status_code == 200
        data = resp.json()
        assert "run_id" in data
        assert data.get("status") in ("running", "waiting_approval", "completed")
        if "reply" in data and data["reply"]:
            assert len(data["reply"]) > 0
    except Exception as e:
        print(f"WARNING: chat smoketest failed: {e}")

if __name__ == "__main__":
    test_policy()
    test_store()
    test_chat_endpoint()
    print("test_agent_v2: OK")
