import pytest
import os
import json
from pathlib import Path
from runtime.integrations.templates import TemplateStore

@pytest.fixture
def store(tmp_path):
    # Pass a specific path to avoid writing to ~/.brynq in tests
    return TemplateStore(db_path=tmp_path / "templates.json")

def test_save_and_load(store):
    chain_config = {"steps": [{"model": "claude", "prompt": "hello"}]}
    tid = store.save("test_template", chain_config, "A test template")
    loaded = store.load(tid)
    assert loaded is not None
    assert loaded["name"] == "test_template"
    assert loaded["chain_config"] == chain_config

def test_export_import_roundtrip(store, tmp_path):
    chain_config = {"steps": [{"model": "gpt-4o", "prompt": "hi"}]}
    tid = store.save("export_me", chain_config, "Will be exported")
    
    export_path = tmp_path / "exported.json"
    store.export_to_file(tid, str(export_path))
    
    assert export_path.exists()
    
    new_tid = store.import_from_file(str(export_path))
    assert new_tid != tid
    
    imported = store.load(new_tid)
    assert imported["name"] == "export_me"
    assert imported["chain_config"] == chain_config

def test_update_version(store):
    chain_config_1 = {"steps": [{"model": "v1"}]}
    tid = store.save("versioned", chain_config_1)
    
    chain_config_2 = {"steps": [{"model": "v2"}]}
    v2 = store.update_version(tid, chain_config_2)
    assert v2 == 2
    
    chain_config_3 = {"steps": [{"model": "v3"}]}
    v3 = store.update_version(tid, chain_config_3)
    assert v3 == 3
    
    loaded = store.load(tid)
    assert loaded["version"] == 3
    assert loaded["chain_config"] == chain_config_3
    assert len(loaded["versions"]) == 2
