import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT

def recreate_logs_table(conn_info, retention_days=30):
    """
    Elimina y recrea la tabla 'logs' en TimescaleDB con configuración optimizada.
    Incluye:
      - Hypertable por 'timestamp'
      - Índices por service, timestamp y level
      - Políticas de compresión y retención automáticas
    """

    conn = psycopg2.connect(**conn_info)
    conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
    cur = conn.cursor()

    print("⚠️  Eliminando tabla 'logs' si existe...")
    cur.execute("DROP TABLE IF EXISTS logs CASCADE;")

    print("🔧 Creando tabla 'logs'...")
    cur.execute("""
        CREATE TABLE logs (
            id BIGSERIAL,
            service TEXT NOT NULL,
            level TEXT NOT NULL,
            message TEXT NOT NULL,
            timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
            metadata JSONB
        );
    """)

    print("🧱 Configurando hypertable 'logs'...")
    cur.execute("""
        SELECT create_hypertable('logs', 'timestamp', if_not_exists => TRUE);
    """)

    print("⚡ Creando índices...")
    cur.execute("""
        CREATE INDEX IF NOT EXISTS idx_logs_service_timestamp
        ON logs (service, timestamp DESC);
    """)
    cur.execute("""
        CREATE INDEX IF NOT EXISTS idx_logs_level
        ON logs (level);
    """)
    cur.execute("""
        CREATE INDEX IF NOT EXISTS idx_logs_timestamp
        ON logs (timestamp DESC);
    """)

    print("📦 Activando compresión...")
    cur.execute("""
        ALTER TABLE logs SET (
            timescaledb.compress,
            timescaledb.compress_segmentby = 'service'
        );
    """)

    print("🗓️  Añadiendo políticas automáticas...")
    cur.execute("""
        SELECT add_compression_policy('logs', INTERVAL '7 days');
    """)
    cur.execute(f"""
        SELECT add_retention_policy('logs', INTERVAL '{retention_days} days');
    """)


    conn.commit()
    cur.close()
    conn.close()

    print("✅ Tabla 'logs' recreada y configurada correctamente.")



# Ejecutar la configuración al ejecutar el script directamente


if __name__ == "__main__":


    conn_info = {
        "dbname": "basededatos",
        "user": "postgres",
        "password": "mipassword",
        "host": "localhost",
        "port": 55432,
    }

    recreate_logs_table(conn_info, retention_days=90)