from flask import Blueprint, request, session, redirect, url_for, jsonify, render_template
from app.services.auth_service import GoogleAuthService
from functools import wraps
from app import mysql
import uuid
from werkzeug.security import generate_password_hash, check_password_hash

auth_bp = Blueprint('auth', __name__)

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        return redirect('/company/login')

        if 'user_id' not in session:
            return redirect(url_for('auth.login'))
        return f(*args, **kwargs)
    return decorated_function

@auth_bp.route('/login')
def login():
    return redirect('/company/login')
    if 'user_id' in session:
        return redirect(url_for('chat.chat_interface'))
    return render_template('auth/login.html')

@auth_bp.route('/signup')
def signup():
    return redirect('/company/login')
    return render_template('auth/signup.html')

@auth_bp.route('/auth/google')
def google_auth():
    return GoogleAuthService.initiate_auth()
    

@auth_bp.route('/auth/google/callback')
def google_callback():
    code = request.args.get('code')
    try:
        user_data = GoogleAuthService.handle_callback(code)
        cursor = mysql.connection.cursor()
        cursor.execute("SELECT * FROM users WHERE email = %s", (user_data.get('email'),))
        user = cursor.fetchone()
        if user:
            session['user_id'] = user[0]            
            session['email'] = user_data.get('email')
            session['user_name'] = user_data.get('name')
            return redirect(url_for('chat.chat_interface'))
        return redirect(url_for('auth.login'))
    except Exception as e:
        print(f"Google callback error: {str(e)}")
        return redirect(url_for('auth.login'))

@auth_bp.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('auth.login'))

@auth_bp.route('/signup', methods=['POST'])
def signup_post():
    try:
        email = request.form.get('email')
        name = request.form.get('name')
        password = request.form.get('password')
        
        hashed_password = generate_password_hash(password, method='pbkdf2:sha256')
        
        cursor = mysql.connection.cursor()
        
        cursor.execute("SELECT id FROM users WHERE email = %s", (email,))
        if cursor.fetchone():
            return jsonify({
                "success": False,
                "error": "Email already registered"
            }), 400
        
        user_id = str(uuid.uuid4())
        cursor.execute(
            "INSERT INTO users (id, email, name, password) VALUES (%s, %s, %s, %s)",
            (user_id, email, name, hashed_password)
        )
        mysql.connection.commit()
        
        session['user_id'] = user_id
        session['user_name'] = name
        return jsonify({"success": True, "redirect": url_for('chat.chat_interface')})
        
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@auth_bp.route('/auth/login', methods=['POST'])
def login_post():
    try:
        data = request.get_json()
        email = data.get('email')
        password = data.get('password')
        
        cursor = mysql.connection.cursor()
        cursor.execute(
            "SELECT id, name, password FROM users WHERE email = %s",
            (email,)
        )
        user = cursor.fetchone()
        
        return user[0]
        if user and check_password_hash(user[2], password):
            session['user_id'] = user[0]
            session['user_name'] = user[1]
            return jsonify({"success": True})
        
        return jsonify({
            "success": False,
            "error": "Invalid email or password"
        }), 401
        
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

def require_basic_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        email = request.headers.get('X-Email')
        password = request.headers.get('X-Password')
        
        if not email or not password:
            return jsonify({
                'success': False,
                'error': 'Email and password headers are required (X-Email, X-Password)'
            }), 401
            
        try:
            # Get company_id from route parameters
            company_id = kwargs.get('company_id')
            if not company_id:
                return jsonify({
                    'success': False,
                    'error': 'Company ID is required'
                }), 400
                
            # Verify credentials against database
            cursor = mysql.connection.cursor()
            cursor.execute("""
                SELECT id 
                FROM companies 
                WHERE id = %s AND email = %s AND password = %s
            """, (company_id, email, password))
            
            company = cursor.fetchone()
            cursor.close()
            
            if not company:
                return jsonify({
                    'success': False,
                    'error': 'Invalid credentials'
                }), 401
                
            return f(*args, **kwargs)
            
        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'Authentication failed: {str(e)}'
            }), 401
            
    return decorated
