"""
Database system for Deep-Ocean-NEXUS
"""

import sqlite3
from datetime import datetime
from typing import List, Dict, Any
import json

class NexusDatabase:
    """SQLite database for system data"""
    
    def __init__(self, db_path: str = "data/nexus.db"):
        self.db_path = db_path
        self._init_database()
    
    def _init_database(self):
        """Initialize database tables"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # Sensor readings table
        cursor.execute('''
        CREATE TABLE IF NOT EXISTS sensor_readings (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
            pressure_kpa REAL,
            temperature_c REAL,
            salinity_psu REAL,
            depth_m REAL,
            sensor_id TEXT
        )
        ''')
        
        # System logs table
        cursor.execute('''
        CREATE TABLE IF NOT EXISTS system_logs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
            level TEXT,
            module TEXT,
            message TEXT,
            data TEXT
        )
        ''')
        
        # Decisions table
        cursor.execute('''
        CREATE TABLE IF NOT EXISTS decisions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
            decision_id TEXT,
            layer TEXT,
            decision_data TEXT,
            confidence REAL
        )
        ''')
        
        conn.commit()
        conn.close()
    
    def save_sensor_reading(self, reading: Dict[str, Any]):
        """Save sensor reading to database"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
        INSERT INTO sensor_readings 
        (pressure_kpa, temperature_c, salinity_psu, depth_m, sensor_id)
        VALUES (?, ?, ?, ?, ?)
        ''', (
            reading.get('pressure_kpa'),
            reading.get('temperature_c'),
            reading.get('salinity_psu'),
            reading.get('depth_m'),
            reading.get('sensor_id', 'hydro_001')
        ))
        
        conn.commit()
        conn.close()
    
    def save_system_log(self, level: str, module: str, message: str, data: dict = None):
        """Save system log"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
        INSERT INTO system_logs (level, module, message, data)
        VALUES (?, ?, ?, ?)
        ''', (level, module, message, json.dumps(data) if data else None))
        
        conn.commit()
        conn.close()
    
    def save_decision(self, decision_id: str, layer: str, decision_data: dict, confidence: float):
        """Save decision record"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
        INSERT INTO decisions (decision_id, layer, decision_data, confidence)
        VALUES (?, ?, ?, ?)
        ''', (decision_id, layer, json.dumps(decision_data), confidence))
        
        conn.commit()
        conn.close()
    
    def get_recent_sensor_data(self, limit: int = 100) -> List[Dict]:
        """Get recent sensor data"""
        conn = sqlite3.connect(self.db_path)
        conn.row_factory = sqlite3.Row
        cursor = conn.cursor()
        
        cursor.execute('''
        SELECT * FROM sensor_readings 
        ORDER BY timestamp DESC 
        LIMIT ?
        ''', (limit,))
        
        rows = cursor.fetchall()
        conn.close()
        
        return [dict(row) for row in rows]
    
    def get_system_stats(self) -> Dict[str, Any]:
        """Get system statistics"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # Count readings
        cursor.execute('SELECT COUNT(*) FROM sensor_readings')
        reading_count = cursor.fetchone()[0]
        
        # Count logs by level
        cursor.execute('''
        SELECT level, COUNT(*) as count 
        FROM system_logs 
        GROUP BY level
        ''')
        log_counts = dict(cursor.fetchall())
        
        # Latest timestamp
        cursor.execute('SELECT MAX(timestamp) FROM sensor_readings')
        latest_timestamp = cursor.fetchone()[0]
        
        conn.close()
        
        return {
            'sensor_readings_count': reading_count,
            'log_counts': log_counts,
            'latest_reading': latest_timestamp,
            'database_size_kb': self._get_database_size()
        }
    
    def _get_database_size(self) -> float:
        """Get database file size in KB"""
        import os
        if os.path.exists(self.db_path):
            return os.path.getsize(self.db_path) / 1024
        return 0.0
