import subprocess
import json
import time
import pytest

BASE_URL = "http://localhost:5000"

def run_curl(method, endpoint, data=None, token=None):
    cmd = ["curl", "-s", "-X", method, f"{BASE_URL}{endpoint}"]
    cmd += ["-H", "Content-Type: application/json"]
    if token:
        cmd += ["-H", f"Authorization: Bearer {token}"]
    if data:
        cmd += ["-d", json.dumps(data)]
    
    result = subprocess.run(cmd, capture_output=True, text=True)
    try:
        return json.loads(result.stdout)
    except:
        return result.stdout

def test_full_flow():
    # 1. Register
    username = f"testuser_{int(time.time())}"
    print(f"Testing Register with {username}...")
    reg_data = {
        "username": username,
        "email": f"{username}@example.com",
        "password": "testpassword123"
    }
    reg_res = run_curl("POST", "/api/v1/auth/register", data=reg_data)
    assert "access_token" in reg_res
    
    token = reg_res["access_token"]

    # 2. Create Memo
    memo_data = {
        "content": "Hello world from integration test!",
        "visibility": "PRIVATE"
    }
    memo_res = run_curl("POST", "/api/v1/memos", data=memo_data, token=token)
    assert memo_res["content"] == memo_data["content"]
    assert "id" in memo_res

    # 3. List Memos
    list_res = run_curl("GET", "/api/v1/memos", token=token)
    assert len(list_res) >= 1
    print("✅ Integration test PASSED!")

if __name__ == "__main__":
    test_full_flow()
