"""
Web Integration - Eden can interact with the internet
"""
import requests
import json
from datetime import datetime

class WebIntegration:
    def __init__(self):
        self.session = requests.Session()
        self.request_history = []
        
    def fetch_url(self, url, method="GET", **kwargs):
        """Make HTTP request"""
        try:
            response = self.session.request(method, url, **kwargs)
            
            result = {
                "success": True,
                "status_code": response.status_code,
                "url": url,
                "method": method,
                "timestamp": datetime.now().isoformat()
            }
            
            # Try to parse JSON
            try:
                result["data"] = response.json()
            except:
                result["data"] = response.text[:1000]  # First 1000 chars
            
            self.request_history.append(result)
            return result
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "url": url,
                "timestamp": datetime.now().isoformat()
            }
    
    def fetch_json(self, url):
        """Fetch and parse JSON API"""
        return self.fetch_url(url, method="GET")
    
    def post_data(self, url, data):
        """POST data to API"""
        return self.fetch_url(url, method="POST", json=data)
    
    def get_request_stats(self):
        """Statistics on API usage"""
        total = len(self.request_history)
        successful = sum(1 for r in self.request_history if r["success"])
        
        return {
            "total_requests": total,
            "successful": successful,
            "failed": total - successful,
            "success_rate": successful / total if total > 0 else 0
        }

if __name__ == "__main__":
    print("WEB INTEGRATION TEST")
    
    web = WebIntegration()
    
    # Test with a public API
    print("\n🌐 Testing web connectivity...")
    result = web.fetch_json("https://api.github.com/zen")
    
    if result["success"]:
        print(f"   ✅ Successfully connected to web")
        print(f"   Status: {result['status_code']}")
    else:
        print(f"   ⚠️  Network test (may need internet)")
    
    stats = web.get_request_stats()
    print(f"\n📊 Request Stats:")
    print(f"   Total: {stats['total_requests']}")
    print(f"   Successful: {stats['successful']}")
    
    print("\n🌐 Eden can now:")
    print("   - Make HTTP requests")
    print("   - Fetch JSON APIs")
    print("   - POST data to services")
    print("   - Track web interactions")
    
    print("\n✅ WEB INTEGRATION OPERATIONAL")
