"""
TAS License Checker - Simple Web UI
Upload file and solve CAPTCHA only
"""

import os
import sys
import subprocess
import threading
import time
import json
import glob
from flask import render_template, request, jsonify
from werkzeug.utils import secure_filename

# Configuration
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'csv', 'xlsx', 'xls'}

# Ensure directories exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs('templates', exist_ok=True)

# Global variable to track processing status
processing_status = {
    'is_processing': False,
    'status': 'idle',
    'message': 'Ready to process files',
    'progress': 0,
    'captcha_url': None
}

def allowed_file(filename):
    """Check if file extension is allowed"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def run_scraper_script(file_path, scraper_type, userId='', entityType='', userRole=''):
    """Run the appropriate scraper script based on type"""
    global processing_status
    
    try:
        processing_status['is_processing'] = True
        processing_status['status'] = 'processing'
        processing_status['message'] = f'Starting {scraper_type.upper()} data processing...'
        
        # Create status file path and job ID
        job_id = f"job_{int(time.time())}"
        status_file = f"status_{job_id}.json"
        
        # Route to appropriate scraper
        if scraper_type == 'tas':
            script_name = 'captchaScrapper/tas_web.py'
        elif scraper_type == 'nsw':
            script_name = 'captchaScrapper/nsw_web.py'
        elif scraper_type == 'qld':
            script_name = 'captchaScrapper/qld_web.py'
        elif scraper_type == 'vic':
            script_name = 'captchaScrapper/vic_web.py'
        elif scraper_type == 'act':
            script_name = 'captchaScrapper/act_web.py'
        else:
            # Default to TAS if scraper type not recognized
            script_name = 'captchaScrapper/tas_web.py'
            scraper_type = 'tas'
        
        # Run the web-compatible scraper script
        print(f"Running: {sys.executable} {script_name} {file_path} {job_id} {status_file}")
        
        # Start the process from the main project directory
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        process = subprocess.Popen([
            sys.executable, script_name, file_path, job_id, status_file, userId, entityType, userRole
        ], cwd=project_root)
        
        # Monitor status file for updates
        while process.poll() is None:
            try:
                if os.path.exists(status_file):
                    with open(status_file, 'r') as f:
                        status_data = json.load(f)
                        processing_status['status'] = status_data.get('status', 'processing')
                        processing_status['message'] = status_data.get('message', f'{scraper_type.upper()} processing...')
                        if 'progress' in status_data:
                            processing_status['progress'] = status_data['progress']
                        if 'captcha_url' in status_data:
                            processing_status['captcha_url'] = status_data['captcha_url']
                            processing_status['message'] = 'CAPTCHA detected! Please solve it in the browser window.'
            except Exception as e:
                print(f"Error reading status file: {e}")
            
            time.sleep(2)  # Check every 2 seconds
        
        # Wait for process to complete
        return_code = process.wait()
        
        print(f"Process completed with return code: {return_code}")
        
        # Set final status based on return code
        if return_code == 0:
            processing_status['status'] = 'completed'
            processing_status['message'] = f'{scraper_type.upper()} processing completed successfully!'
            
            # Clean up uploaded file after successful processing
            try:
                if os.path.exists(file_path):
                    os.remove(file_path)
                    print(f"Cleaned up uploaded file: {file_path}")
            except Exception as e:
                print(f"Error cleaning up uploaded file: {e}")
        else:
            processing_status['status'] = 'error'
            processing_status['message'] = f'{scraper_type.upper()} processing failed with return code: {return_code}'
            
        # Clean up status file
        try:
            if os.path.exists(status_file):
                os.remove(status_file)
                print(f"Cleaned up status file: {status_file}")
        except Exception as e:
            print(f"Error cleaning up status file: {e}")
            
    except Exception as e:
        processing_status['status'] = 'error'
        processing_status['message'] = f'{scraper_type.upper()} processing failed: {str(e)}'
        
        # Clean up uploaded file on error as well
        try:
            if os.path.exists(file_path):
                os.remove(file_path)
                print(f"Cleaned up uploaded file after error: {file_path}")
        except Exception as cleanup_error:
            print(f"Error cleaning up uploaded file after error: {cleanup_error}")
    
    finally:
        processing_status['is_processing'] = False

def run_tas_script(file_path):
    """Run the tas_web.py script with the uploaded file (legacy function)"""
    return run_scraper_script(file_path, 'tas')

def register_web_ui_routes(app):
    """Register web UI routes with the main Flask app"""
    
    @app.route('/scraper')
    def index():
        """Main page - File data upload and processing"""
        return render_template('upload.html')
    
    @app.route('/upload', methods=['POST'])
    def upload_file():
        """Handle file upload with scraper selection"""
        global processing_status
        
        if processing_status['is_processing']:
            return jsonify({'error': 'Already processing a file. Please wait.'}), 400
        
        if 'file' not in request.files:
            return jsonify({'error': 'No file uploaded'}), 400
        
        # Get scraper parameter from form data
        scraper_type = request.form.get('state', 'tas').lower()
        userId = request.form.get('userId', '')
        entityType = request.form.get('entityType', '')
        userRole = request.form.get('userRole', '')

        print("UserId:", userId)
        print("Entity Type:", entityType)
        print("User Role:", userRole)
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': 'No file selected'}), 400
        
        if not allowed_file(file.filename):
            return jsonify({'error': 'Invalid file type. Please upload CSV or Excel files.'}), 400
        
        try:
            # Save uploaded file
            filename = secure_filename(file.filename)
            file_path = os.path.join(UPLOAD_FOLDER, filename)
            file.save(file_path)
            
            # Reset processing status
            processing_status = {
                'is_processing': True,
                'status': 'uploaded',
                'message': f'File uploaded successfully. Starting {scraper_type.upper()} processing...'
            }
            
            # Start processing in background thread with scraper selection
            thread = threading.Thread(target=run_scraper_script, args=(file_path, scraper_type, userId, entityType, userRole))
            thread.daemon = True
            thread.start()
            
            return jsonify({
                'success': True,
                'message': f'File uploaded successfully. {scraper_type.upper()} processing started.',
                'scraper': scraper_type
            })
            
        except Exception as e:
            return jsonify({'error': f'Upload failed: {str(e)}'}), 500
    
    @app.route('/status')
    def get_status():
        """Get current processing status"""
        return jsonify(processing_status)
    
    @app.route('/reset')
    def reset_status():
        """Reset processing status"""
        global processing_status
        processing_status = {
            'is_processing': False,
            'status': 'idle',
            'message': 'Ready to process files',
            'progress': 0,
            'captcha_url': None
        }
        return jsonify({'success': True, 'message': 'Status reset'})
    
    @app.route('/cleanup')
    def cleanup_status_files():
        """Clean up status files"""
        try:
            status_files = glob.glob("status_*.json")
            cleaned_count = 0
            for file in status_files:
                try:
                    os.remove(file)
                    cleaned_count += 1
                    print(f"Cleaned up status file: {file}")
                except:
                    pass
            return jsonify({'success': True, 'cleaned_files': cleaned_count})
        except Exception as e:
            return jsonify({'success': False, 'error': str(e)})
    
    @app.route('/cleanup-uploads')
    def cleanup_uploaded_files():
        """Clean up any leftover uploaded files"""
        try:
            upload_files = glob.glob("uploads/*.csv")
            cleaned_count = 0
            for file in upload_files:
                try:
                    os.remove(file)
                    cleaned_count += 1
                    print(f"Cleaned up uploaded file: {file}")
                except:
                    pass
            return jsonify({'success': True, 'cleaned_files': cleaned_count})
        except Exception as e:
            return jsonify({'success': False, 'error': str(e)})
    
    @app.route('/captcha-solved', methods=['POST'])
    def mark_captcha_solved():
        """Mark CAPTCHA as solved manually"""
        try:
            # Find the current status file
            status_files = glob.glob("status_*.json")
            if not status_files:
                return jsonify({'error': 'No active processing found'}), 400
            
            # Update the most recent status file
            latest_status_file = max(status_files, key=os.path.getctime)
            
            # Read current status
            with open(latest_status_file, 'r') as f:
                status_data = json.load(f)
            
            # Update status to continue processing
            status_data['status'] = 'processing'
            status_data['message'] = 'CAPTCHA solved, continuing processing...'
            status_data['captcha_detected'] = False
            
            # Write updated status
            with open(latest_status_file, 'w') as f:
                json.dump(status_data, f, indent=2)
            
            return jsonify({'success': True, 'message': 'CAPTCHA marked as solved'})
            
        except Exception as e:
            return jsonify({'error': f'Failed to mark CAPTCHA as solved: {str(e)}'}), 500

# Legacy support - if run directly, create a standalone app
if __name__ == '__main__':
    from flask import Flask
    app = Flask(__name__)
    app.secret_key = 'tas_license_checker_secret'
    register_web_ui_routes(app)
    
    print("Starting TAS License Checker Web UI...")
    print("Open your browser and go to: http://localhost:5000")
    app.run(debug=True, host='0.0.0.0', port=5000)