"""Auth - sign-in with throttling/lockout, sign-out and session bootstrap."""
import os
import secrets
import sys
import time
from datetime import datetime, timedelta, timezone

from flask import Blueprint, render_template, request, redirect, url_for, session
from werkzeug.security import generate_password_hash, check_password_hash

sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from core import (get_db, audit_event, DEMO_MODE, LOGIN_MAX_FAILURES, LOGIN_WINDOW_MINUTES,
                  LOGIN_MAX_FAILURES_PER_ADDRESS, logger)

bp = Blueprint('auth', __name__)
GENERIC_ERROR = 'Invalid username or password'
LOCKED_ERROR = 'Too many failed sign-in attempts. Try again later or ask an administrator.'
# Compared against when the username does not exist, so response timing does not reveal valid accounts.
_DUMMY_HASH = generate_password_hash(secrets.token_urlsafe(16))


def _window_start():
    return (datetime.now(timezone.utc) - timedelta(minutes=LOGIN_WINDOW_MINUTES)).strftime('%Y-%m-%d %H:%M:%S')


def is_locked(conn, username, remote_addr):
    """Failures since the last success for this username, or from this address, within the window."""
    since = _window_start()
    last_ok = conn.execute('SELECT MAX(id) FROM login_attempts WHERE username=? AND success=1',
                           (username,)).fetchone()[0] or 0
    user_failures = conn.execute('SELECT COUNT(*) FROM login_attempts WHERE username=? AND success=0 '
                                 'AND created_at >= ? AND id > ?', (username, since, last_ok)).fetchone()[0]
    addr_failures = conn.execute('SELECT COUNT(*) FROM login_attempts WHERE remote_addr=? AND success=0 '
                                 'AND created_at >= ?', (remote_addr, since)).fetchone()[0]
    return user_failures >= LOGIN_MAX_FAILURES or addr_failures >= LOGIN_MAX_FAILURES_PER_ADDRESS


def _record_attempt(conn, username, remote_addr, success):
    conn.execute('INSERT INTO login_attempts (username, remote_addr, success, created_at) VALUES (?,?,?,?)',
                 (username, remote_addr, int(success), datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')))
    # Keep the table small: attempts older than 30 days are not needed for throttling.
    conn.execute("DELETE FROM login_attempts WHERE created_at < datetime('now','-30 days')")


@bp.route('/login', methods=['GET', 'POST'])
def login():
    if DEMO_MODE:
        return redirect(url_for('dashboard.index'))
    error = 'Your session expired. Please sign in again.' if request.args.get('expired') else None
    status = 200

    if request.method == 'POST':
        username = (request.form.get('username') or '').strip()[:80]
        password = request.form.get('password') or ''
        remote_addr = request.remote_addr or 'unknown'
        conn = get_db()
        try:
            if is_locked(conn, username, remote_addr):
                _record_attempt(conn, username, remote_addr, False)
                audit_event('login.blocked', 'identity', username, f'addr={remote_addr}', conn)
                conn.commit()
                logger.warning('Blocked sign-in for %r from %s (lockout window)', username, remote_addr)
                return render_template('login.html', error=LOCKED_ERROR), 429

            user = conn.execute('SELECT * FROM users WHERE username = ?', (username,)).fetchone()
            valid = check_password_hash(user['password_hash'] if user else _DUMMY_HASH, password)
            if user and user['is_active'] and valid:
                _record_attempt(conn, username, remote_addr, True)
                conn.execute('UPDATE users SET last_login_at = CURRENT_TIMESTAMP WHERE id = ?', (user['id'],))
                session.clear()
                session.permanent = True
                session['user_id'] = user['id']
                session['username'] = user['username']
                session['_csrf_token'] = secrets.token_urlsafe(32)
                session['_started'] = session['_last_seen'] = time.time()
                audit_event('login', 'identity', user['username'], f'addr={remote_addr}', conn, actor_user_id=user['id'])
                conn.commit()
                return redirect(url_for('dashboard.index'))

            _record_attempt(conn, username, remote_addr, False)
            audit_event('login.failed', 'identity', username,
                        'inactive account' if user and valid else 'bad credentials', conn)
            conn.commit()
            error, status = GENERIC_ERROR, 401
        finally:
            conn.close()

    return render_template('login.html', error=error), status


@bp.route('/logout', methods=['POST'])
def logout():
    if session.get('user_id'):
        audit_event('logout', 'identity', session.get('username', ''))
    session.clear()
    return redirect(url_for('auth.login'))
