#!/usr/bin/env python3
"""
Buffer Auto-Post Server
Run this on your computer to enable automated posting from OpenClaw

Usage:
    python3 buffer_server.py
    
Then OpenClaw can call:
    curl -X POST http://localhost:8765/post \
      -H "Content-Type: application/json" \
      -d '{"text": "Your post content", "profile": "instagram"}'
"""

import json
import os
import time
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs

# Configuration
BUFFER_ACCESS_TOKEN = "6meMcsFtohrsqtN0L4W5uo6-gJq6-HLJtb5Q4-b2xrs"
PORT = 8765

# Cache the profiles on startup
profiles_cache = None

def get_buffer_profiles():
    """Get connected social media profiles from Buffer"""
    import requests
    
    url = "https://api.bufferapp.com/1/profiles.json"
    headers = {"Authorization": f"Bearer {BUFFER_ACCESS_TOKEN}"}
    
    try:
        response = requests.get(url, headers=headers, timeout=10)
        if response.status_code == 200:
            return response.json()
        else:
            print(f"Error getting profiles: {response.status_code} - {response.text}")
            return []
    except Exception as e:
        print(f"Error: {e}")
        return []

def create_buffer_update(text, profile_id=None):
    """Create a new update in Buffer"""
    import requests
    
    url = "https://api.bufferapp.com/1/updates/create.json"
    headers = {"Authorization": f"Bearer {BUFFER_ACCESS_TOKEN}"}
    
    data = {"text": text}
    if profile_id:
        data["profile_ids[]"] = [profile_id]
    
    try:
        response = requests.post(url, headers=headers, data=data, timeout=10)
        if response.status_code in [200, 201]:
            return {"success": True, "response": response.json()}
        else:
            return {"success": False, "error": f"{response.status_code}: {response.text}"}
    except Exception as e:
        return {"success": False, "error": str(e)}

class BufferHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        """Handle GET requests"""
        parsed = urlparse(self.path)
        
        if parsed.path == "/profiles":
            # Return cached profiles
            global profiles_cache
            if profiles_cache is None:
                profiles_cache = get_buffer_profiles()
            
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps(profiles_cache).encode())
            
        elif parsed.path == "/health":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({"status": "ok"}).encode())
            
        else:
            self.send_response(404)
            self.end_headers()
    
    def do_POST(self):
        """Handle POST requests"""
        content_length = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(content_length)
        
        try:
            data = json.loads(body.decode())
        except:
            data = {}
        
        parsed = urlparse(self.path)
        
        if parsed.path == "/post":
            # Create a new post
            text = data.get("text", "")
            profile_id = data.get("profile_id")
            
            if not text:
                self.send_response(400)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps({"error": "No text provided"}).encode())
                return
            
            result = create_buffer_update(text, profile_id)
            
            self.send_response(200 if result.get("success") else 500)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps(result).encode())
            
        elif parsed.path == "/refresh-profiles":
            # Force refresh profiles cache
            global profiles_cache
            profiles_cache = get_buffer_profiles()
            
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({"profiles": profiles_cache}).encode())
            
        else:
            self.send_response(404)
            self.end_headers()
    
    def log_message(self, format, *args):
        """Custom log format"""
        print(f"[{self.log_date_time_string()}] {format % args}")

def main():
    """Start the server"""
    global profiles_cache
    
    # Initial profile fetch
    print("Fetching Buffer profiles...")
    profiles_cache = get_buffer_profiles()
    
    if profiles_cache:
        print(f"Found {len(profiles_cache)} connected profiles:")
        for p in profiles_cache:
            print(f"  - {p.get('service', 'Unknown')}: {p.get('formatted_username', 'N/A')}")
    else:
        print("Warning: Could not fetch profiles. Check API token.")
    
    # Start server
    server = HTTPServer(('0.0.0.0', PORT), BufferHandler)
    print(f"\n🚀 Buffer Auto-Post Server running on http://localhost:{PORT}")
    print(f"\nEndpoints:")
    print(f"  GET  /profiles     - List connected profiles")
    print(f"  GET  /health       - Health check")
    print(f"  POST /post         - Create new post")
    print(f"       Body: {{'text': '...', 'profile_id': 'optional'}}")
    print(f"  POST /refresh-profiles - Refresh profile cache")
    print(f"\nPress Ctrl+C to stop\n")
    
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nStopping server...")
        server.shutdown()

if __name__ == "__main__":
    main()
