import hashlib
import secrets
import smtplib
from datetime import datetime, timedelta, timezone
from email.message import EmailMessage
from urllib.parse import urlsplit

from flask import Blueprint, current_app, flash, jsonify, redirect, render_template, request, url_for
from werkzeug.security import generate_password_hash

from app.extensions import csrf, db, limiter
from app.models.password_reset import PasswordResetToken
from app.models.user import User


auth_reset_bp = Blueprint('auth_reset', __name__)
GENERIC_RESPONSE = {'message': 'If the email is registered, reset instructions will be sent.'}


def _send_reset_email(user, token):
    settings = current_app.config
    required = ('MAIL_SERVER', 'MAIL_DEFAULT_SENDER', 'PUBLIC_BASE_URL')
    if not all(settings.get(key) for key in required):
        current_app.logger.warning('Password reset email is not configured.')
        return False

    base_url = urlsplit(settings['PUBLIC_BASE_URL'])
    if (base_url.scheme not in {'http', 'https'} or not base_url.netloc
            or base_url.username or base_url.password
            or (base_url.scheme != 'https' and base_url.hostname not in {'localhost', '127.0.0.1'})):
        current_app.logger.error('PUBLIC_BASE_URL must be an absolute HTTP(S) URL.')
        return False
    reset_path = url_for('auth_reset.reset_password', token=token)
    reset_url = f"{settings['PUBLIC_BASE_URL'].rstrip('/')}{reset_path}"
    message = EmailMessage()
    message['Subject'] = 'Reset your NGO Foundation password'
    message['From'] = settings['MAIL_DEFAULT_SENDER']
    message['To'] = user.email
    message.set_content(
        'Use the following link within one hour to reset your password. '
        'If you did not request this, you can ignore this message.\n\n'
        f'{reset_url}\n'
    )

    with smtplib.SMTP(settings['MAIL_SERVER'], settings.get('MAIL_PORT', 587), timeout=10) as smtp:
        if settings.get('MAIL_USE_TLS', True):
            smtp.starttls()
        if settings.get('MAIL_USERNAME'):
            smtp.login(settings['MAIL_USERNAME'], settings.get('MAIL_PASSWORD', ''))
        smtp.send_message(message)
    return True


def _create_reset_token(email):
    if not isinstance(email, str) or not email.strip():
        return False
    user = User.query.filter(
        User.email == email.strip().lower(),
        User.status.in_(('active', 'invited')),
    ).first()
    if user is None:
        return False

    token = secrets.token_urlsafe(32)
    now = datetime.now(timezone.utc).replace(tzinfo=None)
    reset = PasswordResetToken(
        user_id=user.id,
        token_hash=hashlib.sha256(token.encode('utf-8')).hexdigest(),
        expires_at=now + timedelta(hours=1),
    )
    db.session.add(reset)
    db.session.commit()
    try:
        sent = _send_reset_email(user, token)
    except (OSError, smtplib.SMTPException):
        db.session.rollback()
        current_app.logger.exception('Could not send password reset email.')
        sent = False
    if not sent:
        reset.used_at = datetime.now(timezone.utc).replace(tzinfo=None)
        db.session.commit()
    return sent


@auth_reset_bp.route('/api/v1/auth/forgot-password', methods=['POST'])
@csrf.exempt
@limiter.limit('3 per hour')
def api_forgot_password():
    data = request.get_json(silent=True) or {}
    _create_reset_token(data.get('email') if isinstance(data, dict) else None)
    return jsonify(GENERIC_RESPONSE), 200


@auth_reset_bp.route('/forgot-password', methods=['GET', 'POST'])
@limiter.limit('3 per hour', methods=['POST'])
def forgot_password():
    if request.method == 'POST':
        _create_reset_token(request.form.get('email'))
        flash(GENERIC_RESPONSE['message'], 'info')
        return redirect(url_for('auth_reset.forgot_password'))
    return render_template('auth/forgot_password.html')


@auth_reset_bp.route('/reset-password/<token>', methods=['GET', 'POST'])
def reset_password(token):
    token_hash = hashlib.sha256(token.encode('utf-8')).hexdigest()
    reset = PasswordResetToken.query.filter_by(token_hash=token_hash, used_at=None).first()
    now = datetime.now(timezone.utc).replace(tzinfo=None)
    if reset is None or reset.expires_at <= now:
        flash('This password reset link is invalid or has expired.', 'error')
        return render_template('auth/reset_password.html', token=None), 400

    if request.method == 'POST':
        password = request.form.get('password', '')
        confirmation = request.form.get('confirm_password', '')
        if len(password) < 12:
            flash('Choose a password with at least 12 characters.', 'error')
        elif password != confirmation:
            flash('The passwords do not match.', 'error')
        else:
            user = db.session.get(User, reset.user_id)
            if user is None or user.status not in {'active', 'invited'}:
                flash('This password reset link is invalid or has expired.', 'error')
                return render_template('auth/reset_password.html', token=None), 400
            user.password_hash = generate_password_hash(password)
            user.status = 'active'
            reset.used_at = now
            db.session.commit()
            flash('Your password has been updated. Please sign in.', 'success')
            return redirect(url_for('auth.login'))

    return render_template('auth/reset_password.html', token=token)


@auth_reset_bp.route('/api/v1/auth/reset-password', methods=['POST'])
@csrf.exempt
@limiter.limit('5 per hour')
def api_reset_password():
    """
    Validates a single-use token and sets a new password via the REST API.
    Fulfills Section 10 REST API endpoint POST /api/v1/auth/reset-password.
    """
    data = request.get_json(silent=True) or {}
    if not isinstance(data, dict):
        return jsonify({'error': 'A JSON object is required'}), 400

    token = data.get('token')
    password = data.get('password', '')
    confirmation = data.get('confirm_password', '')

    if not isinstance(token, str) or not token.strip():
        return jsonify({'error': 'A valid reset token is required'}), 400

    token_hash = hashlib.sha256(token.strip().encode('utf-8')).hexdigest()
    reset = PasswordResetToken.query.filter_by(token_hash=token_hash, used_at=None).first()
    now = datetime.now(timezone.utc).replace(tzinfo=None)

    # Check for token existence and expiration
    if reset is None or reset.expires_at <= now:
        return jsonify({'error': 'This password reset token is invalid or has expired'}), 400

    # Validate password complexity and confirmation match
    if not isinstance(password, str) or len(password) < 12:
        return jsonify({'error': 'Password must be at least 12 characters long'}), 400
    if confirmation and password != confirmation:
        return jsonify({'error': 'The passwords do not match'}), 400

    user = db.session.get(User, reset.user_id)
    if user is None or user.status not in {'active', 'invited'}:
        return jsonify({'error': 'This password reset token is invalid or has expired'}), 400

    # Update credentials, activate account if invited, and consume the reset token
    user.password_hash = generate_password_hash(password)
    user.status = 'active'
    reset.used_at = now
    db.session.commit()

    return jsonify({'message': 'Password has been reset successfully. You may now sign in.'}), 200
