#!/usr/bin/env python3
"""
Complexity Analyzer - Assesses database complexity to guide analysis depth
Combines ideas from iter8's adaptive approach with iter2's comprehensive assessment
"""

import sqlite3
import os
import json

def analyze_complexity():
    """Analyze database complexity and determine appropriate analysis mode."""
    
    db_path = './database.sqlite'
    if not os.path.exists(db_path):
        print("ERROR: database.sqlite not found")
        return
    
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    complexity_score = 0
    complexity_factors = []
    
    # 1. Count tables
    cursor.execute("SELECT COUNT(*) FROM sqlite_master WHERE type='table'")
    table_count = cursor.fetchone()[0]
    
    if table_count <= 5:
        complexity_factors.append(f"Simple: Only {table_count} tables")
    elif table_count <= 10:
        complexity_score += 1
        complexity_factors.append(f"Medium: {table_count} tables")
    else:
        complexity_score += 2
        complexity_factors.append(f"Complex: {table_count} tables")
    
    # 2. Check for junction tables (many-to-many relationships)
    cursor.execute("""
        SELECT name FROM sqlite_master 
        WHERE type='table' 
        AND (name LIKE '%\_%' OR name LIKE '%To%' OR name LIKE '%Map%')
    """)
    junction_tables = cursor.fetchall()
    if junction_tables:
        complexity_score += 1
        complexity_factors.append(f"Junction tables detected: {len(junction_tables)}")
    
    # 3. Check for complex naming (spaces, mixed case)
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
    tables = cursor.fetchall()
    complex_names = [t[0] for t in tables if ' ' in t[0] or any(c.isupper() for c in t[0][1:])]
    if complex_names:
        complexity_score += 1
        complexity_factors.append(f"Complex naming conventions: {complex_names[:3]}")
    
    # 4. Count total relationships (foreign keys)
    fk_count = 0
    for table in tables:
        cursor.execute(f"PRAGMA foreign_key_list({table[0]})")
        fks = cursor.fetchall()
        fk_count += len(fks)
    
    if fk_count > 20:
        complexity_score += 2
        complexity_factors.append(f"High relationship count: {fk_count} foreign keys")
    elif fk_count > 10:
        complexity_score += 1
        complexity_factors.append(f"Moderate relationships: {fk_count} foreign keys")
    
    # 5. Check for large tables
    large_tables = []
    for table in tables:
        try:
            cursor.execute(f"SELECT COUNT(*) FROM [{table[0]}]")
            count = cursor.fetchone()[0]
            if count > 100000:
                large_tables.append((table[0], count))
        except:
            pass
    
    if large_tables:
        complexity_score += 1
        complexity_factors.append(f"Large tables: {large_tables[:3]}")
    
    # 6. Check for temporal data (date/time columns)
    temporal_columns = 0
    for table in tables:
        cursor.execute(f"PRAGMA table_info([{table[0]}])")
        columns = cursor.fetchall()
        for col in columns:
            col_name = col[1].lower()
            col_type = col[2].lower()
            if 'date' in col_name or 'time' in col_name or 'date' in col_type or 'time' in col_type:
                temporal_columns += 1
    
    if temporal_columns > 10:
        complexity_score += 1
        complexity_factors.append(f"Heavy temporal data: {temporal_columns} date/time columns")
    
    # Determine analysis mode
    if complexity_score <= 1:
        mode = "CONCISE"
        description = "Simple database - use concise analysis"
    elif complexity_score <= 3:
        mode = "BALANCED"
        description = "Medium complexity - use balanced analysis"
    else:
        mode = "COMPREHENSIVE"
        description = "Complex database - use comprehensive analysis"
    
    # Output results
    os.makedirs('./tool_output', exist_ok=True)
    
    result = {
        'mode': mode,
        'complexity_score': complexity_score,
        'table_count': table_count,
        'factors': complexity_factors,
        'description': description
    }
    
    with open('./tool_output/complexity_analysis.json', 'w') as f:
        json.dump(result, f, indent=2)
    
    print(f"COMPLEXITY ANALYSIS COMPLETE")
    print(f"Mode: {mode}")
    print(f"Score: {complexity_score}/10")
    print(f"Tables: {table_count}")
    print(f"Recommendation: {description}")
    print("\nComplexity Factors:")
    for factor in complexity_factors:
        print(f"  - {factor}")
    
    conn.close()

if __name__ == "__main__":
    analyze_complexity()