import sqlite3
import json
import gzip
import logging
import requests

class CloudSync:
    def __init__(self, api_url: str = "https://api.brynq.ai/v1/sync"):
        self.api_url = api_url

    def sync_exocortex(self, db_path: str) -> bool:
        """
        Reads data from the local exocortex timeline DB, compresses it,
        and sends it to the cloud. Returns True if sync was successful, False otherwise.
        """
        try:
            conn = sqlite3.connect(db_path)
            conn.row_factory = sqlite3.Row
            cursor = conn.cursor()
            
            # Check if timeline table exists first
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='timeline'")
            if not cursor.fetchone():
                conn.close()
                return True # Nothing to sync if table doesn't exist
                
            cursor.execute("SELECT * FROM timeline")
            rows = [dict(row) for row in cursor.fetchall()]
            conn.close()

            if not rows:
                return True

            payload_json = json.dumps({"data": rows}).encode('utf-8')
            compressed_payload = gzip.compress(payload_json)

            headers = {
                'Content-Type': 'application/json',
                'Content-Encoding': 'gzip'
            }
            
            response = requests.post(
                self.api_url,
                data=compressed_payload,
                headers=headers,
                timeout=10
            )

            response.raise_for_status()
            return True

        except Exception as e:
            logging.error(f"Sync failed for db {db_path}: {e}")
            return False
