#!/usr/bin/env python3
"""Fix corrupted SQLite database by recreating it."""

import os
import sys
import json
from pathlib import Path

# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root / "src"))

from proxym.storage import SQLiteNamespaceStore
from proxym.config import get_settings

def main():
    # Get data directory - proxym uses ~/.local/share/proxym by default
    data_dir = Path.home() / ".local" / "share" / "proxym"
    
    print(f"Data directory: {data_dir}")
    
    # Remove corrupted database if it exists
    corrupted_db = data_dir / "proxym_corrupted.sqlite"
    if corrupted_db.exists():
        print(f"Keeping corrupted database at: {corrupted_db}")
    
    # Create new database by initializing a store
    new_db = data_dir / "proxym.sqlite"
    
    # Test each namespace
    namespaces = [
        'tickets', 'sprints', 'milestones', 'projects', 'environments',
        'env_assignments', 'accounts', 'users', 'tool_overrides', 'tool_jobs',
        'domain_events'
    ]
    
    print("Initializing new database...")
    store = SQLiteNamespaceStore(str(new_db))
    
    for namespace in namespaces:
        try:
            # Test write by loading and saving
            data = store.load_namespace(namespace)
            store.save_namespace(namespace, data)
            print(f"✓ Namespace '{namespace}' initialized")
        except Exception as e:
            print(f"✗ Failed to initialize namespace '{namespace}': {e}")
    
    print(f"\nNew database created at: {new_db}")
    print("Please restart the proxym service to begin using the new database.")
    
    # Try to import tickets from JSON if exists
    tickets_json = data_dir / "tickets.json"
    if tickets_json.exists():
        print("\nAttempting to restore tickets from JSON backup...")
        try:
            with open(tickets_json) as f:
                tickets_data = json.load(f)
            
            if 'tickets' in tickets_data:
                tickets = tickets_data['tickets']
                store.save_namespace('tickets', tickets)
                print(f"✓ Restored {len(tickets)} tickets from JSON backup")
        except Exception as e:
            print(f"✗ Failed to restore tickets: {e}")

if __name__ == "__main__":
    main()
