import requests
import sys
import os
import json

# Configuration
BASE_URL = "http://localhost:5001"
API_KEY = os.environ.get('OPENCLAW_API_KEY', 'change_this_to_a_secure_key')

def list_stories():
    """Fetches and prints stories for the agent to read."""
    try:
        headers = {'X-API-Key': API_KEY}
        response = requests.get(f"{BASE_URL}/api/stories", headers=headers)
        
        if response.status_code == 200:
            stories = response.json()
            print(f"Found {len(stories)} recent stories:")
            for story in stories:
                print(f"[{story['id']}] {story['created_at']}: {story['content'][:50]}...")
        else:
            print(f"Error: {response.status_code} - {response.text}")
    except Exception as e:
        print(f"Connection failed: {e}")

def post_story(content):
    """Posts a new story on behalf of the agent."""
    try:
        headers = {'X-API-Key': API_KEY, 'Content-Type': 'application/json'}
        payload = {'content': content}
        
        response = requests.post(f"{BASE_URL}/api/post", headers=headers, json=payload)
        
        if response.status_code == 201:
            print("Success: Story posted.")
            print(response.json())
        else:
            print(f"Failed to post: {response.status_code}")
            print(response.text)
    except Exception as e:
        print(f"Connection failed: {e}")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python openclaw_bridge.py [list|post] [content]")
        sys.exit(1)

    command = sys.argv[1]

    if command == "list":
        list_stories()
    elif command == "post":
        if len(sys.argv) < 3:
            print("Error: 'post' requires content argument.")
        else:
            post_story(sys.argv[2])
    else:
        print(f"Unknown command: {command}")