import os
import httpx
import pytest
from conftest import BASE_URL, ADMIN_PASSWORD

def _headers():
    uid = os.getenv("SYNC_TEST_USER_ID", "")
    return {"X-User-ID": uid}

def test_logout():
    with httpx.Client(timeout=10.0) as client:
        r = client.post(f"{BASE_URL}/users/logout", headers=_headers())
        assert r.status_code == 200
        assert r.json()["message"] == "Logged out successfully"

def test_password_update():
    with httpx.Client(timeout=10.0) as client:
        # Update password
        update_payload = {
            "current_password": ADMIN_PASSWORD,
            "new_password": "new_admin_password"
        }
        r = client.put(f"{BASE_URL}/users/password", json=update_payload, headers=_headers())
        assert r.status_code == 200, f"Expected 200 OK, got {r.status_code}: {r.text}"
        
        # Revert it back
        revert_payload = {
            "current_password": "new_admin_password",
            "new_password": ADMIN_PASSWORD
        }
        r = client.put(f"{BASE_URL}/users/password", json=revert_payload, headers=_headers())
        assert r.status_code == 200, f"Failed to revert password: {r.text}"

def test_config_export_import():
    with httpx.Client(timeout=10.0) as client:
        # 1. Export Config
        r = client.get(f"{BASE_URL}/users/me/config/export", headers=_headers())
        assert r.status_code == 200, f"Export failed: {r.text}"
        yaml_content = r.content
        
        # 2. Import Config
        files = {'file': ('cortex_config.yaml', yaml_content, 'application/x-yaml')}
        r = client.post(f"{BASE_URL}/users/me/config/import", files=files, headers=_headers())
        assert r.status_code == 200, f"Import failed: {r.text}"
        
        assert "llm" in r.json()
