#!/usr/bin/env python3
"""
Test script for analyze_db.py

This script demonstrates how to use the analyze_db.py script to analyze
the project's SQLite database and recover it if issues are found.

Usage:
    python test_analyze_db.py [--recovery] [--advanced]

Options:
    --recovery  Automatically attempt recovery if issues are found
    --advanced  Use advanced recovery techniques (multiple methods)
"""

import os
import sys
import argparse
import subprocess
from pathlib import Path

# Get the project root directory
project_root = Path(__file__).parent.parent.parent.absolute()

# Path to the database file
db_path = os.path.join(project_root, "data", "database", "sqlite.db")

# Path to the analyze_db.py script
analyze_script = os.path.join(project_root, "src", "scripts", "analyze_db.py")

# Path to the log_db directory
log_db_dir = os.path.join(os.path.dirname(__file__), "log_db")

# Create log_db directory if it doesn't exist
if not os.path.exists(log_db_dir):
    os.makedirs(log_db_dir)
    print(f"Created log directory: {log_db_dir}")

def main():
    """Run the analyze_db.py script on the project's database with optional recovery."""
    # Parse command line arguments
    parser = argparse.ArgumentParser(description='Test the analyze_db.py script on the project database.')
    parser.add_argument('--recovery', action='store_true', 
                        help='Automatically attempt recovery if issues are found')
    parser.add_argument('--advanced', action='store_true',
                        help='Use advanced recovery techniques (multiple methods)')
    args = parser.parse_args()

    print(f"Project root: {project_root}")
    print(f"Database path: {db_path}")
    print(f"Analysis script: {analyze_script}")
    print(f"Log directory: {log_db_dir}")

    # Check if the database file exists
    if not os.path.exists(db_path):
        print(f"Error: Database file not found at {db_path}")
        return 1

    # Check if the analyze_db.py script exists
    if not os.path.exists(analyze_script):
        print(f"Error: Analysis script not found at {analyze_script}")
        return 1

    # Prepare command with optional arguments
    cmd = [sys.executable, analyze_script, db_path]

    if args.recovery:
        cmd.append('--recovery')
        print("Recovery mode enabled: Will automatically attempt recovery if issues are found.")

    if args.advanced:
        cmd.append('--advanced')
        print("Advanced recovery mode enabled: Will use multiple recovery techniques.")

    print("\nRunning database analysis...")

    # Run the analyze_db.py script
    try:
        # Change to the log_db directory to make logs save there
        current_dir = os.getcwd()
        os.chdir(log_db_dir)

        result = subprocess.run(
            cmd,
            check=True,
            text=True,
            capture_output=True
        )

        # Change back to the original directory
        os.chdir(current_dir)

        # Print the output
        print("\nAnalysis output:")
        print(result.stdout)

        if result.stderr:
            print("\nErrors:")
            print(result.stderr)

        print("\nAnalysis completed successfully.")
        print(f"Log files have been saved to: {log_db_dir}")
        return 0
    except subprocess.CalledProcessError as e:
        print(f"\nError running analysis: {e}")
        if e.stdout:
            print("\nOutput:")
            print(e.stdout)
        if e.stderr:
            print("\nErrors:")
            print(e.stderr)
        print(f"Log files have been saved to: {log_db_dir}")
        return 1

if __name__ == "__main__":
    sys.exit(main())
