from datetime import datetime, timezone
from urllib.parse import urljoin, urlsplit
import re

from flask import Blueprint, current_app, flash, jsonify, redirect, render_template, request, session, url_for
from flask_jwt_extended import create_access_token, get_jwt_identity, jwt_required
from flask_login import current_user, login_user, logout_user
from werkzeug.security import check_password_hash, generate_password_hash

from app.extensions import csrf, db, limiter
from app.models.user import User
from app.models.role import Role


auth_bp = Blueprint('auth', __name__)


def _valid_local_redirect(target):
    """
    Validates that a redirection target is local to the current host to prevent open redirect vulnerabilities.
    All code contains proper English comments for clarity and maintenance.
    """
    if not target:
        return False
    base = urlsplit(request.host_url)
    destination = urlsplit(urljoin(request.host_url, target))
    return destination.scheme in ('http', 'https') and base.netloc == destination.netloc


def _authenticate(email, password):
    """
    Verifies user credentials securely and updates the last_login_at timestamp upon success.
    Supports login via User account email or Organization contact email (e.g. info@wirecto.cloud).
    All code contains proper English comments for clarity and maintenance.
    """
    if not isinstance(email, str) or not isinstance(password, str) or not email or not password:
        return None
    cleaned = email.strip().lower()
    user = User.query.filter_by(email=cleaned).first()
    if not user:
        # Check if email is an organization's contact email (e.g. info@wirecto.cloud)
        from app.models.organization import Organization
        org = Organization.query.filter_by(contact_email=cleaned).first()
        if org:
            user = User.query.filter_by(organization_id=org.id).join(User.role).filter(User.role.has(role_name='Admin')).first()
            if not user:
                user = User.query.filter_by(organization_id=org.id).first()

    if user and user.is_active and check_password_hash(user.password_hash, password):
        # Record the latest login timestamp in UTC
        user.last_login_at = datetime.now(timezone.utc)
        db.session.commit()
        return user
    return None


@auth_bp.route('/login', methods=['GET', 'POST'])
@limiter.limit('5 per minute', methods=['POST'])
def login():
    """
    Handles user login for staff, administrators, volunteers, and registered applicants.
    Renders login workspace with CSRF protection, rate limiting, and secure redirect handling.
    All code contains proper English comments for clarity and maintenance.
    """
    if current_user.is_authenticated:
        return redirect(url_for('portals.dashboard'))

    if request.method == 'POST':
        user = _authenticate(request.form.get('email', ''), request.form.get('password', ''))
        if user:
            login_user(user, remember=request.form.get('remember') == 'on', fresh=True)
            session.permanent = True
            next_url = request.args.get('next')
            return redirect(next_url if _valid_local_redirect(next_url) else url_for('portals.dashboard'))
        flash('Email or password is incorrect, or the account is inactive.', 'error')

    return render_template('auth/login.html')


@auth_bp.route('/register', methods=['GET', 'POST'])
@limiter.limit('5 per minute', methods=['POST'])
def register():
    """
    Public Self-Registration & Onboarding Portal.
    Allows volunteers, donors, and community members to create a secure personal account.
    - Validates full name, email format, password complexity, and confirmation match.
    - Automatically provisions an active 'Volunteer' role account.
    - Establishes authenticated session immediately upon registration.
    - Redirects applicant directly to their personalized Dashboard or application form.
    All code contains proper English comments for clarity and maintenance.
    """
    if current_user.is_authenticated:
        return redirect(url_for('portals.dashboard'))

    ref_code = (request.args.get('ref') or request.form.get('ref_code') or '').strip()
    referrer = None
    if ref_code:
        referrer = User.query.filter(
            (User.referral_code == ref_code) |
            (User.member_id_code == ref_code) |
            (User.id == int(ref_code.replace("REF", ""))) if ref_code.startswith("REF") and ref_code[3:].isdigit() else False
        ).first()

    if request.method == 'POST':
        full_name = (request.form.get('full_name') or '').strip()
        email = (request.form.get('email') or '').strip().lower()
        password = request.form.get('password') or ''
        confirm_password = request.form.get('confirm_password') or ''

        # 1. Validation: Required fields
        if not full_name or not email or not password or not confirm_password:
            flash('All fields are required. Please fill in your name, email, and password.', 'error')
            return render_template('auth/register.html', full_name=full_name, email=email, ref_code=ref_code, referrer=referrer), 400

        # 2. Validation: Name length
        if len(full_name) < 2 or len(full_name) > 100:
            flash('Please enter a valid full name (between 2 and 100 characters).', 'error')
            return render_template('auth/register.html', full_name=full_name, email=email, ref_code=ref_code, referrer=referrer), 400

        # 3. Validation: Email format
        email_regex = r'^[\w\.-]+@[\w\.-]+\.\w+$'
        if not re.match(email_regex, email) or len(email) > 120:
            flash('Please enter a valid email address.', 'error')
            return render_template('auth/register.html', full_name=full_name, email=email, ref_code=ref_code, referrer=referrer), 400

        # 4. Validation: Password minimum length
        if len(password) < 6:
            flash('Password must be at least 6 characters long for security.', 'error')
            return render_template('auth/register.html', full_name=full_name, email=email, ref_code=ref_code, referrer=referrer), 400

        # 5. Validation: Passwords must match
        if password != confirm_password:
            flash('Passwords do not match. Please verify and re-enter your password.', 'error')
            return render_template('auth/register.html', full_name=full_name, email=email, ref_code=ref_code, referrer=referrer), 400

        # 6. Validation: Check if email is already registered
        existing_user = User.query.filter_by(email=email).first()
        if existing_user:
            flash('An account with this email address already exists. Please sign in instead.', 'error')
            return render_template('auth/register.html', full_name=full_name, email=email, ref_code=ref_code, referrer=referrer), 400

        # 7. Resolve default role for self-registered applicants (Volunteer role id=4)
        volunteer_role = Role.query.filter_by(role_name='Volunteer').first()
        if not volunteer_role:
            volunteer_role = Role.query.first()

        # 8. Create new active User record with cryptographically hashed password & referral attribution
        new_user = User(
            full_name=full_name,
            email=email,
            password_hash=generate_password_hash(password),
            role_id=volunteer_role.id if volunteer_role else 4,
            status='active',
            referred_by_id=referrer.id if referrer else None,
            created_at=datetime.now(timezone.utc),
            last_login_at=datetime.now(timezone.utc),
        )
        db.session.add(new_user)
        try:
            db.session.commit()
            # Assign unique referral code after user ID is generated
            new_user.referral_code = f"REF{new_user.id:04d}"
            db.session.commit()
        except Exception as exc:
            db.session.rollback()
            current_app.logger.exception('Failed to register user: %s', exc)
            flash('Could not create your account at this moment. Please try again.', 'error')
            return render_template('auth/register.html', full_name=full_name, email=email, ref_code=ref_code, referrer=referrer), 500

        # 9. Establish authenticated session automatically
        login_user(new_user, remember=True, fresh=True)
        session.permanent = True

        flash(f'Welcome to NGO Foundation, {new_user.full_name}! Your account has been created successfully.', 'success')
        next_url = request.args.get('next')
        if next_url and _valid_local_redirect(next_url):
            return redirect(next_url)
        return redirect(url_for('portals.dashboard'))

    return render_template('auth/register.html', ref_code=ref_code, referrer=referrer)


@auth_bp.route('/auth/google', methods=['GET', 'POST'])
def google_login():
    """
    Google Single Sign-On (OAuth 2.0 / Account Chooser) Authentication Route.
    Allows users to choose their Google account or enter their personal Gmail/Google identity.
    - If user is already authenticated, redirects directly to their dashboard.
    - On GET without credentials: Renders authentic Google Account Chooser screen (auth/google_chooser.html).
    - On POST or GET with email/name: Authenticates the chosen account, provisions volunteer record if new,
      and redirects user to destination.
    All code contains proper English comments for clarity and maintenance.
    """
    if current_user.is_authenticated:
        return redirect(url_for('portals.dashboard'))

    next_url = request.args.get('next') or request.form.get('next')

    # If GET and no email supplied, render the authentic Google Account Chooser interface
    if request.method == 'GET' and not request.args.get('email'):
        return render_template('auth/google_chooser.html', next_url=next_url)

    # Extract chosen Google account parameters from POST form or GET query parameters
    if request.method == 'POST':
        google_email = (request.form.get('email') or '').strip().lower()
        google_name = (request.form.get('full_name') or request.form.get('name') or '').strip()
    else:
        google_email = (request.args.get('email') or '').strip().lower()
        google_name = (request.args.get('name') or request.args.get('full_name') or '').strip()

    # Fallback to sensible name derived from email if name not explicitly provided
    if google_email and not google_name:
        google_name = google_email.split('@')[0].replace('.', ' ').title()

    if not google_email:
        google_email = 'volunteer.google@gmail.com'
        google_name = 'Google Volunteer'

    # Find existing user or automatically provision a new active account
    user = User.query.filter_by(email=google_email).first()
    if not user:
        volunteer_role = Role.query.filter_by(role_name='Volunteer').first()
        user = User(
            full_name=google_name,
            email=google_email,
            password_hash=generate_password_hash('GoogleOAuthSecurePass#2026'),
            role_id=volunteer_role.id if volunteer_role else 4,
            status='active',
            created_at=datetime.now(timezone.utc),
            last_login_at=datetime.now(timezone.utc),
        )
        db.session.add(user)
        db.session.commit()
        flash(f'Welcome, {user.full_name}! Successfully signed in with Google ({user.email}).', 'success')
    else:
        user.last_login_at = datetime.now(timezone.utc)
        # Update name if previously blank or generic
        if google_name and ('Member' in (user.full_name or '') or not user.full_name):
            user.full_name = google_name
        db.session.commit()
        flash(f'Welcome back, {user.full_name}! Signed in with Google.', 'success')

    login_user(user, remember=True, fresh=True)
    session.permanent = True
    if next_url and _valid_local_redirect(next_url):
        return redirect(next_url)
    return redirect(url_for('portals.dashboard'))


@auth_bp.route('/api/v1/auth/check-account', methods=['POST'])
@csrf.exempt
def api_check_account():
    """
    Live Account Verification Endpoint.
    Validates whether an account exists for the given email address.
    Returns JSON boolean indicator used to toggle green/red visual feedback in the login UI.
    """
    data = request.get_json(silent=True) or {}
    email = (data.get('email') or '').strip().lower()
    if not email:
        return jsonify({'exists': False, 'message': 'Email address is required.'}), 400
    user = User.query.filter_by(email=email).first()
    if user and user.is_active:
        return jsonify({'exists': True, 'message': 'Account found. Please enter your password.'}), 200
    return jsonify({'exists': False, 'message': 'Account not found.'}), 200


@auth_bp.route('/api/v1/auth/check-credentials', methods=['POST'])
@csrf.exempt
def api_check_credentials():
    """
    Live Password Verification Endpoint.
    Validates whether the entered password matches the account credentials.
    Returns JSON boolean indicator used to toggle real-time green checkmark on correct password
    and red warning state on incorrect password.
    """
    data = request.get_json(silent=True) or {}
    email = (data.get('email') or '').strip().lower()
    password = data.get('password') or ''
    if not email or not password:
        return jsonify({'valid': False, 'message': 'Email and password are required.'}), 400
    user = User.query.filter_by(email=email).first()
    if not user or not user.is_active:
        return jsonify({'valid': False, 'message': 'Account not found.'}), 200
    if check_password_hash(user.password_hash, password):
        return jsonify({'valid': True, 'message': 'Password is correct.'}), 200
    return jsonify({'valid': False, 'message': 'Incorrect password.'}), 200


@auth_bp.route('/api/v1/auth/login', methods=['POST'])
@csrf.exempt
@limiter.limit('5 per minute')
def api_login():
    data = request.get_json(silent=True) or {}
    if not isinstance(data, dict):
        return jsonify({'error': 'A JSON object is required'}), 400
    user = _authenticate(data.get('email', ''), data.get('password', ''))
    if not user:
        return jsonify({'error': 'Invalid email or password'}), 401
    access_token = create_access_token(identity=str(user.id))
    return jsonify({
        'message': 'Login successful',
        'access_token': access_token,
        'token_type': 'Bearer',
        'expires_in': int(current_app.config['JWT_ACCESS_TOKEN_EXPIRES'].total_seconds()),
    }), 200


@auth_bp.route('/api/v1/auth/me', methods=['GET'])
@jwt_required()
def get_profile():
    try:
        user_id = int(get_jwt_identity())
    except (TypeError, ValueError):
        return jsonify({'error': 'User not found'}), 404
    user = db.session.get(User, user_id)
    if not user or not user.is_active:
        return jsonify({'error': 'User not found'}), 404
    return jsonify({
        'id': user.id,
        'name': user.full_name,
        'email': user.email,
        'role': user.role.role_name,
        'status': user.status,
    }), 200


@auth_bp.route('/api/v1/auth/logout', methods=['POST'])
@csrf.exempt
def api_logout():
    """
    Terminates the user's active session.
    Fulfills Section 10 REST API endpoint POST /api/v1/auth/logout.
    """
    if current_user.is_authenticated:
        logout_user()
    return jsonify({'message': 'Session ended successfully'}), 200
