"""Database management for RoastBuddy."""

import sqlite3
from datetime import datetime
from pathlib import Path
from typing import Optional, Dict, Any, List
from roastbuddy.core.config import get_config_dir

DB_FILE = get_config_dir() / "roastbuddy.db"


def get_db_connection() -> sqlite3.Connection:
    """Get a database connection."""
    conn = sqlite3.connect(DB_FILE)
    conn.row_factory = sqlite3.Row
    return conn


def initialize_database():
    """Initialize the database schema."""
    conn = get_db_connection()
    cursor = conn.cursor()
    
    # Commits table
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS commits (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            commit_hash TEXT UNIQUE NOT NULL,
            message TEXT NOT NULL,
            author TEXT NOT NULL,
            timestamp DATETIME NOT NULL,
            files_changed INTEGER DEFAULT 0,
            lines_added INTEGER DEFAULT 0,
            lines_deleted INTEGER DEFAULT 0,
            is_clean BOOLEAN DEFAULT 0,
            repo_path TEXT NOT NULL
        )
    """)
    
    # Streaks table
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS streaks (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            streak_type TEXT NOT NULL,
            current_count INTEGER DEFAULT 0,
            best_count INTEGER DEFAULT 0,
            last_updated DATETIME NOT NULL,
            repo_path TEXT NOT NULL
        )
    """)
    
    # Roasts and praise history
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS interactions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            interaction_type TEXT NOT NULL,
            content TEXT NOT NULL,
            commit_hash TEXT,
            timestamp DATETIME NOT NULL,
            source TEXT NOT NULL,
            repo_path TEXT NOT NULL
        )
    """)
    
    # Achievements/milestones
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS achievements (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            achievement_type TEXT NOT NULL,
            description TEXT NOT NULL,
            earned_at DATETIME NOT NULL,
            repo_path TEXT NOT NULL
        )
    """)
    
    conn.commit()
    conn.close()


def add_commit_record(commit_data: Dict[str, Any]) -> bool:
    """Add a commit record to the database."""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        cursor.execute("""
            INSERT OR REPLACE INTO commits 
            (commit_hash, message, author, timestamp, files_changed, 
             lines_added, lines_deleted, is_clean, repo_path)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            commit_data.get("hash"),
            commit_data.get("message"),
            commit_data.get("author"),
            commit_data.get("timestamp"),
            commit_data.get("files_changed", 0),
            commit_data.get("lines_added", 0),
            commit_data.get("lines_deleted", 0),
            commit_data.get("is_clean", False),
            commit_data.get("repo_path"),
        ))
        
        conn.commit()
        conn.close()
        return True
    except Exception as e:
        print(f"Error adding commit: {e}")
        return False


def add_interaction(interaction_type: str, content: str, commit_hash: Optional[str], 
                    source: str, repo_path: str) -> bool:
    """Add a roast/praise interaction to the database."""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        cursor.execute("""
            INSERT INTO interactions 
            (interaction_type, content, commit_hash, timestamp, source, repo_path)
            VALUES (?, ?, ?, ?, ?, ?)
        """, (
            interaction_type,
            content,
            commit_hash,
            datetime.now().isoformat(),
            source,
            repo_path
        ))
        
        conn.commit()
        conn.close()
        return True
    except Exception as e:
        print(f"Error adding interaction: {e}")
        return False


def get_streak_data(streak_type: str, repo_path: str) -> Optional[Dict[str, Any]]:
    """Get streak data for a specific type."""
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute("""
        SELECT * FROM streaks 
        WHERE streak_type = ? AND repo_path = ?
    """, (streak_type, repo_path))
    
    row = cursor.fetchone()
    conn.close()
    
    if row:
        return dict(row)
    return None


def update_streak(streak_type: str, current_count: int, best_count: int, repo_path: str) -> bool:
    """Update or create a streak record."""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        cursor.execute("""
            INSERT OR REPLACE INTO streaks 
            (streak_type, current_count, best_count, last_updated, repo_path)
            VALUES (?, ?, ?, ?, ?)
        """, (
            streak_type,
            current_count,
            best_count,
            datetime.now().isoformat(),
            repo_path
        ))
        
        conn.commit()
        conn.close()
        return True
    except Exception as e:
        print(f"Error updating streak: {e}")
        return False


def get_recent_interactions(limit: int = 10, repo_path: str = ".") -> List[Dict[str, Any]]:
    """Get recent roast/praise interactions."""
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute("""
        SELECT * FROM interactions 
        WHERE repo_path = ?
        ORDER BY timestamp DESC 
        LIMIT ?
    """, (repo_path, limit))
    
    rows = cursor.fetchall()
    conn.close()
    
    return [dict(row) for row in rows]
