import requests
import json

class CronDB:
    def __init__(self, host='127.0.0.1', port=8080):
        self.url = f"http://{host}:{port}/query"
        # Connection pooling to prevent overhead
        self.session = requests.Session()

    def query(self, sql_string):
        """Sends raw SQL text to the C++ engine"""
        headers = {'Content-Type': 'text/plain'}
        try:
            response = self.session.post(self.url, data=sql_string, headers=headers)
            # Try to return JSON if the C++ engine sent it
            try:
                return response.json()
            except:
                return response.text
        except Exception as e:
            return {"success": False, "message": str(e)}

    def _format(self, val):
        """Translates Python types to CronDB SQL types"""
        if isinstance(val, bool):
            return str(val).lower() # True -> true
        if isinstance(val, (int, float)):
            return str(val)
        if isinstance(val, str):
            # Check for Temporal FSM syntax ( ... --> ... )
            if val.strip().startswith('(') and '-->' in val:
                return val
            return f"'{val}'"
        return str(val)

    def insert(self, table, data):
        fields = " ".join([f"{k}={self._format(v)}" for k, v in data.items()])
        return self.query(f"INSERT INTO {table} {fields}")

    def select(self, table, where=None):
        sql = f"SELECT * FROM {table}"
        if where:
            sql += f" WHERE {where}"
        return self.query(sql)

    def update(self, table, data, where):
        fields = " ".join([f"{k}={self._format(v)}" for k, v in data.items()])
        return self.query(f"UPDATE {table} SET {fields} WHERE {where}")

    def delete(self, table, where):
        return self.query(f"DELETE FROM {table} WHERE {where}")

    def listen(self, table, col, url, where=None):
        sql = f"LISTEN {table} . {col} --> '{url}'"
        if where:
            sql += f" WHERE {where}"
        return self.query(sql)