#!/usr/bin/env python3
"""
Script to find where summarization jobs are stored
"""
from app import app, db
from models import *
import sys

def find_job_everywhere(job_uuid):
    with app.app_context():
        print(f"\n=== SEARCHING FOR JOB {job_uuid} ===\n")
        
        # Check if there's a separate summarization table
        # First, let's see what tables exist
        print("🗄️  Available tables:")
        from sqlalchemy import inspect
        inspector = inspect(db.engine)
        tables = inspector.get_table_names()
        for table in tables:
            print(f"  - {table}")
        
        print(f"\n🔍 Searching for job UUID in all relevant tables...\n")
        
        # 1. Check AnalysisJob table
        job = AnalysisJob.query.filter_by(job_uuid=job_uuid).first()
        if job:
            print(f"✅ Found in AnalysisJob table:")
            print_job_details(job)
            return job
        else:
            print("❌ Not found in AnalysisJob table")
        
        # 2. Check if there might be a separate SummarizationJob table
        try:
            # Try to query for any table that might contain this UUID
            from sqlalchemy import text
            
            # Search in any table that might have job_uuid or similar field
            for table in tables:
                if 'job' in table.lower() or 'summary' in table.lower() or 'analysis' in table.lower():
                    try:
                        # Try common UUID column names
                        for uuid_col in ['job_uuid', 'uuid', 'id', 'job_id']:
                            try:
                                query = text(f"SELECT * FROM {table} WHERE {uuid_col} = :uuid")
                                result = db.session.execute(query, {'uuid': job_uuid}).fetchone()
                                if result:
                                    print(f"✅ Found in table '{table}', column '{uuid_col}':")
                                    print(f"  Result: {dict(result)}")
                                    return result
                            except:
                                pass  # Column doesn't exist or other error
                    except Exception as e:
                        print(f"❌ Error checking table {table}: {str(e)}")
        except Exception as e:
            print(f"❌ Error during table search: {str(e)}")
        
        # 3. Check session storage or temporary files
        print(f"\n📁 Checking for temporary files with UUID {job_uuid}...")
        import os
        upload_folder = app.config.get('UPLOAD_FOLDER', 'uploads')
        if os.path.exists(upload_folder):
            for filename in os.listdir(upload_folder):
                if job_uuid in filename:
                    file_path = os.path.join(upload_folder, filename)
                    file_size = os.path.getsize(file_path)
                    print(f"✅ Found file: {filename} ({file_size} bytes)")
                    print(f"  Path: {file_path}")
        
        # 4. Let's also check if there are any recent jobs
        print(f"\n📋 Recent AnalysisJob entries (last 10):")
        recent_jobs = AnalysisJob.query.order_by(AnalysisJob.created_at.desc()).limit(10).all()
        for job in recent_jobs:
            print(f"  - {job.job_uuid[:8]}... | {job.original_filename} | {job.status} | {job.created_at}")
        
        return None

def print_job_details(job):
    """Print detailed job information"""
    print(f"  UUID: {job.job_uuid}")
    print(f"  Status: {job.status}")
    print(f"  User ID: {job.user_id}")
    print(f"  Filename: {job.original_filename}")
    print(f"  File Path: {job.file_path}")
    print(f"  Created: {job.created_at}")
    print(f"  Error: {job.error_message}")

def check_summarization_route():
    """Check if summarization routes are properly configured"""
    print(f"\n🔧 Checking summarization configuration...")
    
    # Check if summarization blueprint is registered
    from flask import current_app
    blueprints = current_app.blueprints
    print(f"📋 Registered blueprints:")
    for name, bp in blueprints.items():
        print(f"  - {name}: {bp.url_prefix}")
    
    # Check if summarization routes exist
    rules = current_app.url_map.iter_rules()
    summarization_routes = [rule for rule in rules if 'summarization' in rule.rule]
    print(f"\n🛣️  Summarization routes:")
    for route in summarization_routes:
        print(f"  - {route.rule} ({route.methods})")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python find_summarization_job.py <job_uuid>")
        print("  This will search for the job in all possible locations")
        sys.exit(1)
    
    job_uuid = sys.argv[1]
    
    # Search for the job
    result = find_job_everywhere(job_uuid)
    
    # Check summarization configuration
    check_summarization_route()
    
    if not result:
        print(f"\n❌ Job {job_uuid} not found anywhere!")
        print("💡 This suggests either:")
        print("   1. The job was never created in the database")
        print("   2. There's a separate summarization table not being checked")
        print("   3. The job UUID is incorrect")
        print("   4. The summarization feature uses a different storage mechanism")
