import os
try:
    from brynq.rag.rag_engine import ingest_knowledge_base, search_knowledge_base
    HAS_RAG = True
except ImportError:
    HAS_RAG = False

import brynq.hitl_manager as hitl_manager

def execute_python(code: str) -> str:
    """Zero-Trust Quarantined Python Execution."""
    import logging
    from brynq.hitl_manager import request_approval
    logger = logging.getLogger(__name__)
    
    exec_id = request_approval("DATA_SCIENTIST", "execute_python", code)
    if exec_id != -1:
        msg = f"[ZERO-TRUST KERNEL] EXTREME WARNING: Code execution intercepted and quarantined. Task ID: {exec_id}. Awaiting human CEO approval via React Dashboard. You must stop and wait for the user to approve."
        logger.warning(msg)
        return msg
    return "[ZERO-TRUST KERNEL] FATAL ERROR: Failed to quarantine payload. Execution blocked for system safety."

def read_file(filepath: str) -> str:
    try:
        if not os.path.exists(filepath): return f"Error: File '{filepath}' not found."
        with open(filepath, "r", encoding="utf-8") as f: content = f.read()
        return content[:4000] + "\n...[TRUNCATED]" if len(content) > 4000 else content
    except Exception as e: return str(e)

def get_available_tools():
    tools = [
        {"type": "function", "function": {"name": "execute_python", "description": "Propose python code.", "parameters": {"type": "object", "properties": {"code": {"type": "string"}}, "required": ["code"]}}},
        {"type": "function", "function": {"name": "read_file", "description": "Read local file.", "parameters": {"type": "object", "properties": {"filepath": {"type": "string"}}, "required": ["filepath"]}}}
    ]
    if HAS_RAG:
        tools.extend([
            {"type": "function", "function": {"name": "ingest_knowledge_base", "description": "Scans data/knowledge_base and vectorizes all files into long-term memory.", "parameters": {"type": "object", "properties": {}}}},
            {"type": "function", "function": {"name": "search_knowledge_base", "description": "Queries the ChromaDB Vector Matrix for semantic matches.", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}}
        ])
    
    tools.extend([
        {"type": "function", "function": {"name": "search_web", "description": "Search the web for real-time information using DuckDuckGo.", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "The search query."}}, "required": ["query"]}}},
        {"type": "function", "function": {"name": "scrape_url", "description": "Scrape raw text content from a specific URL.", "parameters": {"type": "object", "properties": {"url": {"type": "string", "description": "The URL to scrape."}}, "required": ["url"]}}}
    ])
    return tools



# --- PHASE 10: ENTERPRISE DATABASE CONNECTORS ---
def inspect_sql_schema(db_url: str) -> str:
    """
    Connects to a SQL database (SQLite, Postgres, etc.) and autonomously reflects the schema.
    Returns a list of all tables and their exact column names/types.
    """
    try:
        from sqlalchemy import create_engine, MetaData
        engine = create_engine(db_url)
        metadata = MetaData()
        metadata.reflect(bind=engine)
        
        schema_info = []
        for table in metadata.sorted_tables:
            cols = [f"{c.name} ({c.type})" for c in table.c]
            schema_info.append(f"TABLE: {table.name} | COLUMNS: {', '.join(cols)}")
            
        if not schema_info:
            return "Database connection successful, but zero tables were found."
        return "\n".join(schema_info)
    except Exception as e:
        return f"[DATABASE ERROR] Schema Inspection Failed: {e}"

def execute_sql_query(db_url: str, query: str) -> str:
    """
    Executes a READ-ONLY SQL query against the specified database URL.
    Returns the raw data payload.
    """
    query_lower = query.lower()
    # Zero-Trust SQL Interceptor
    if any(forbidden in query_lower for forbidden in ["drop ", "delete ", "update ", "insert ", "alter ", "truncate "]):
        return "[SECURITY KERNEL INTERCEPT] FATAL ERROR: The DATA_SCIENTIST agent is strictly mathematically restricted to read-only SELECT queries. Modifying the database is forbidden."
        
    try:
        from sqlalchemy import create_engine, text
        engine = create_engine(db_url)
        with engine.connect() as conn:
            result = conn.execute(text(query))
            rows = [dict(row._mapping) for row in result.fetchall()]
            
            if not rows:
                return "Query executed successfully. Zero rows returned."
                
            # Truncate massive enterprise payloads to prevent LLM context-window overflow
            payload = str(rows)
            if len(payload) > 4000:
                return payload[:4000] + "... [DATA TRUNCATED: Payload exceeded 4000 characters. Refine your SQL query using LIMIT or aggregations.]"
            return payload
    except Exception as e:
        return f"[DATABASE ERROR] Query Failed: {e}"

# --- PHASE 10 ENTERPRISE DB CONNECTORS ---
from brynq.db_skills import reflect_database_schema, query_database
