from InvestmentManager.integrator.input_consistency import guarded_route, write_inputs, write_failed, agent_export_changed
from flask import render_template, request, redirect, url_for, session, flash, abort
from InvestmentManager import agents_store, investmentmanager_bp
from InvestmentManager.middleware.session_guard import refresh_password_fingerprint
from InvestmentManager.form_config import (
    flat_apartment_form_fields,
    house_form_fields,
    local_form_fields,
    object_form_fields,
    plot_form_fields,
)
from modules.classes import DatabaseConnectionManager
from modules.core import storage_paths
from modules.core.password_policy import validate_new_password
import os
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash

def _is_master_user():
    return session.get('access_level') == 'master'


@investmentmanager_bp.context_processor
def inject_now():
    return {'now': lambda: datetime.now()}


def _build_dashboard_context():
    active_panel = str(request.args.get('panel') or '').strip()
    if active_panel == 'scheduled-jobs':
        active_panel = 'dbshell'  # Preserve existing bookmarked scheduler links.
    allowed_panels = {
        'scheduled-jobs',
        'export-packages',
        'export-jobs',
        'exports',
        'agents',
        'branches',
        'team',
        'insights',
        'leady',
        'foreign-offers',
        'clients',
        'agent',
        'offers',
        'dodaj',
        'dziennik',
        'leadhunter',
        'dbshell',
    }
    if active_panel not in allowed_panels:
        active_panel = ''

    user_id = session.get('user_id')
    avatar_filename = f'agent_{user_id}.jpg'
    avatar_path = storage_paths.agent_avatar_dir() / avatar_filename
    avatar_url = url_for('static', filename='images/' + avatar_filename) if os.path.exists(avatar_path) else None
    return dict(
        user_id=session.get('user_id'),
        username=session.get('username'),
        first_name=session.get('first_name'),
        last_name=session.get('last_name'),
        access_level=session.get('access_level'),
        active_panel=active_panel,
        avatar_url=avatar_url,
        flat_apartment_form_fields=flat_apartment_form_fields,
        house_form_fields=house_form_fields,
        plot_form_fields=plot_form_fields,
        local_form_fields=local_form_fields,
        object_form_fields=object_form_fields
    )


@investmentmanager_bp.route('/dashboard')
def dashboard():
    if str(request.args.get('panel') or '').strip() in {'exports', 'export-packages', 'export-jobs', 'scheduled-jobs', 'dbshell'} and not _is_master_user():
        abort(403)
    return render_template('investmentmanager/dashboard.html', **_build_dashboard_context())

@investmentmanager_bp.route('/update_profile', methods=['POST'])
@guarded_route
def update_profile():
    try:
        with DatabaseConnectionManager('agents') as conn:
            previous = agents_store.get_agent_contact_row(conn, session['user_id'])
        if previous is None:
            raise ValueError('Agent nie istnieje.')
        email = request.form.get('email', previous[0])
        phone = request.form.get('telefon', previous[1])
        license_number = request.form.get('licencja', previous[2])
        if agent_export_changed(session['user_id'], dict(email=email, phone=phone, license=license_number)):
            write_inputs(agent_id=session['user_id'], media=False)
        with DatabaseConnectionManager('agents') as conn:
            cursor = conn.cursor()

            # Zmiana danych kontaktowych
            agents_store.update_agent_contact(cursor, session['user_id'], email, phone, license_number,
                                              datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))

            # Zmiana hasła – jeśli podano dane
            current_password = request.form.get('current_password')
            new_password = request.form.get('new_password')
            confirm_password = request.form.get('confirm_password')

            messages = []
            changed_password_hash = None

            if current_password and new_password and confirm_password:
                current_row = agents_store.get_agent_password_row(cursor, session['user_id'])
                current_hash = current_row[0] if current_row else None
                policy_error = None
                if current_row:
                    policy_error = validate_new_password(
                        new_password, login=current_row[1], first_name=current_row[2], last_name=current_row[3],
                        email=email, phone=phone, licence=license_number)

                if not current_hash or not check_password_hash(current_hash, current_password):
                    messages.append('❌ Błędne aktualne hasło.')
                elif new_password != confirm_password:
                    messages.append('❌ Nowe hasła się nie zgadzają.')
                elif policy_error:
                    messages.append(f'❌ {policy_error}')
                else:
                    new_hash = generate_password_hash(new_password)
                    agents_store.set_agent_password_hash(cursor, session['user_id'], new_hash,
                                                         datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
                    changed_password_hash = new_hash
                    messages.append('✅ Hasło zostało zmienione.')

            # DatabaseConnectionManager closes without committing: contact data and
            # (if any) the new password are saved here, before the session or any
            # success message reflects them. A failed commit goes to the except below.
            conn.commit()

            if changed_password_hash is not None:
                # The user's own sessions elsewhere die on their next request; this one stays valid.
                refresh_password_fingerprint(changed_password_hash)

            # Kontaktowe dane zmieniane niezależnie – ale nie rób flasha tutaj
            session['email'] = email
            session['phone'] = phone
            session['licence'] = license_number

            # Na końcu: flash zbiorczy
            if messages:
                flash(' '.join(messages), 'info')
            else:
                flash('✅ Dane zostały zaktualizowane.', 'success')

    except Exception as e:
        write_failed()
        flash('Błąd przy aktualizacji danych.', 'error')
        print(f"Błąd aktualizacji profilu: {e}")

    return redirect(url_for('investmentmanager.dashboard'))

@investmentmanager_bp.route('/upload_avatar', methods=['POST'])
@guarded_route
def upload_avatar():
    avatar = request.files.get('avatar')
    if avatar and session.get('user_id'):
        try:
            user_id = session['user_id']
            filename = f'agent_{user_id}.jpg'
            filepath = storage_paths.agent_avatar_dir() / filename
            write_inputs(agent_id=user_id)
            avatar.save(filepath)
            flash('Zdjęcie zostało zaktualizowane.', 'success')
        except Exception as e:
            write_failed()
            flash('Błąd przy zapisie zdjęcia.', 'error')
            print(f"Błąd uploadu avatara: {e}")
    else:
        flash('Nieprawidłowe żądanie zdjęcia.', 'error')

    return redirect(url_for('investmentmanager.dashboard'))


@investmentmanager_bp.route('/dbshell-ui')
def dbshell_ui():
    if not _is_master_user():
        flash('Brak uprawnień do DB Shell.', 'error')
        return redirect(url_for('investmentmanager.dashboard'))
    context = _build_dashboard_context()
    context['active_panel'] = 'dbshell'
    return render_template('investmentmanager/db_shell_page.html', **context)
