from InvestmentManager.integrator.input_consistency import ConsistencyError, guarded_route, write_inputs, agent_export_changed
import sqlite3
from datetime import UTC, datetime
from functools import wraps

from flask import jsonify, request, session
from werkzeug.security import generate_password_hash

from InvestmentManager import agents_store, investmentmanager_bp
from InvestmentManager.middleware.access import is_master
from InvestmentManager.middleware.session_guard import refresh_password_fingerprint
from modules.classes import DatabaseConnectionManager
from modules.core.agent_queries import get_agents, get_branches, get_branches_office_data
from modules.core.error_responses import internal_error_payload
from modules.core.password_policy import generate_initial_password, validate_new_password
from modules.core.session_queries import get_agent_identity, login_exists


ALLOWED_ACCESS_LEVELS = {"agent", "master"}


def _clean_name(value):
    """Trim and collapse inner whitespace ('  Anna   Maria ' -> 'Anna Maria'); None -> ''."""
    return ' '.join(str(value or '').split())


def _login_conflict_response():
    return jsonify({"status": "error", "message": "Agent o takim loginie już istnieje."}), 409


def _internal_error(context, exc):
    """Unexpected failure: generic message + request_id to the client, details (with traceback) to the server log."""
    payload = internal_error_payload(context, exc)
    return {"status": "error", "message": payload["error"], "request_id": payload["request_id"]}


def master_required(view):
    """Account, branch and role administration is master-only (same check as
    dashboard._is_master_user). The CRM blueprint gate already guarantees an
    authenticated session."""
    @wraps(view)
    def wrapper(*args, **kwargs):
        if session.get('access_level') != 'master':
            return jsonify({"status": "error", "message": "Brak uprawnień."}), 403
        return view(*args, **kwargs)
    return wrapper


def _invalid_access_level_response():
    return jsonify({
        "status": "error",
        "message": "Nieprawidłowy poziom dostępu (dozwolone: agent, master).",
    }), 400


def _utc_now() -> str:
    return datetime.now(UTC).strftime("%Y-%m-%d %H:%M:%S")


@investmentmanager_bp.route('/agents_with_branches')
def api_get_agents_with_branches():
    with DatabaseConnectionManager('agents') as conn:
        cursor = conn.cursor()
        payload = agents_store.get_agents_payload(cursor)
    if is_master():
        return jsonify(payload)
    # Agent directory (contact data, access levels) is master-only: anyone else receives just their own record.
    own_id = str(session.get('user_id'))
    return jsonify([agent for agent in payload if str(agent.get('id')) == own_id])


@investmentmanager_bp.route('/agents_panel_meta')
def api_get_agents_panel_meta():
    with DatabaseConnectionManager('agents') as conn:
        cursor = conn.cursor()
        return jsonify(
            {
                "branches": agents_store.get_branches_payload(cursor),
                "roles": agents_store.get_roles_payload(cursor),
            }
        )


@investmentmanager_bp.route('/branches', methods=['GET'])
def api_get_branches():
    with DatabaseConnectionManager('agents') as conn:
        cursor = conn.cursor()
        return jsonify(agents_store.get_branches_payload(cursor))


@investmentmanager_bp.route('/branches', methods=['POST'])
@master_required
def api_add_branch():
    payload = request.get_json(silent=True) or {}
    now_ts = _utc_now()

    name = str(payload.get('name', '')).strip()
    if not name:
        return jsonify({"status": "error", "message": "Nazwa oddziału jest wymagana."}), 400

    title = str(payload.get('title', '')).strip() or f"Oddział {name}"
    info1 = str(payload.get('info1', '')).strip()
    info2 = str(payload.get('info2', '')).strip()
    image_url = str(payload.get('image_url', '')).strip()

    with DatabaseConnectionManager('agents') as conn:
        cursor = conn.cursor()
        existing = agents_store.find_branch_id_by_name(cursor, name)
        if existing:
            return jsonify({"status": "error", "message": "Oddział o tej nazwie już istnieje."}), 400

        agents_store.insert_branch(cursor, name, title, info1, info2, image_url, now_ts)
        conn.commit()

    get_branches.cache_clear()
    get_branches_office_data.cache_clear()
    return jsonify({"status": "success"})


@investmentmanager_bp.route('/branches/<int:branch_id>', methods=['PUT'])
@master_required
def api_update_branch(branch_id):
    payload = request.get_json(silent=True) or {}
    now_ts = _utc_now()

    name = str(payload.get('name', '')).strip()
    if not name:
        return jsonify({"status": "error", "message": "Nazwa oddziału jest wymagana."}), 400

    title = str(payload.get('title', '')).strip() or f"Oddział {name}"
    info1 = str(payload.get('info1', '')).strip()
    info2 = str(payload.get('info2', '')).strip()
    image_url = str(payload.get('image_url', '')).strip()

    with DatabaseConnectionManager('agents') as conn:
        cursor = conn.cursor()

        existing = agents_store.find_other_branch_with_name(cursor, name, branch_id)
        if existing:
            return jsonify({"status": "error", "message": "Inny oddział ma już tę nazwę."}), 400

        agents_store.update_branch(cursor, branch_id, name, title, info1, info2, image_url, now_ts)
        conn.commit()

    get_branches.cache_clear()
    get_branches_office_data.cache_clear()
    return jsonify({"status": "success"})


@investmentmanager_bp.route('/branches/<int:branch_id>', methods=['DELETE'])
@master_required
def api_delete_branch(branch_id):
    with DatabaseConnectionManager('agents') as conn:
        cursor = conn.cursor()
        assigned_count = agents_store.count_branch_assignments(cursor, branch_id)
        if assigned_count > 0:
            return jsonify(
                {
                    "status": "error",
                    "message": f"Nie można usunąć oddziału. Przypisani agenci: {assigned_count}.",
                }
            ), 400

        agents_store.delete_branch(cursor, branch_id)
        conn.commit()

    get_branches.cache_clear()
    get_branches_office_data.cache_clear()
    return jsonify({"status": "success"})


@investmentmanager_bp.route('/roles', methods=['GET'])
def api_get_roles():
    with DatabaseConnectionManager('agents') as conn:
        cursor = conn.cursor()
        return jsonify(agents_store.get_roles_payload(cursor))


@investmentmanager_bp.route('/roles', methods=['POST'])
@master_required
def api_add_role():
    payload = request.get_json(silent=True) or {}
    role_name = str(payload.get('name', '')).strip()
    if not role_name:
        return jsonify({"status": "error", "message": "Nazwa roli jest wymagana."}), 400

    with DatabaseConnectionManager('agents') as conn:
        cursor = conn.cursor()
        existing = agents_store.find_role_id_by_name(cursor, role_name)
        if existing:
            return jsonify({"status": "error", "message": "Rola o tej nazwie już istnieje."}), 400
        agents_store.ensure_role(cursor, role_name)
        conn.commit()

    return jsonify({"status": "success"})


@investmentmanager_bp.route('/roles/<int:role_id>', methods=['PUT'])
@master_required
def api_update_role(role_id):
    payload = request.get_json(silent=True) or {}
    role_name = str(payload.get('name', '')).strip()
    if not role_name:
        return jsonify({"status": "error", "message": "Nazwa roli jest wymagana."}), 400

    with DatabaseConnectionManager('agents') as conn:
        cursor = conn.cursor()
        row = agents_store.get_role_row(cursor, role_id)
        if not row:
            return jsonify({"status": "error", "message": "Rola nie istnieje."}), 404

        existing_name = agents_store.find_other_role_with_name(cursor, role_name, role_id)
        if existing_name:
            return jsonify({"status": "error", "message": "Inna rola ma już tę nazwę."}), 400

        agents_store.update_role(cursor, role_id, role_name)
        conn.commit()

    return jsonify({"status": "success"})


@investmentmanager_bp.route('/roles/<int:role_id>', methods=['DELETE'])
@master_required
def api_delete_role(role_id):
    with DatabaseConnectionManager('agents') as conn:
        cursor = conn.cursor()
        assigned_count = agents_store.count_role_assignments(cursor, role_id)
        if assigned_count > 0:
            return jsonify(
                {
                    "status": "error",
                    "message": f"Nie można usunąć roli. Przypisani agenci: {assigned_count}.",
                }
            ), 400

        agents_store.delete_role(cursor, role_id)
        conn.commit()

    return jsonify({"status": "success"})


@investmentmanager_bp.route('/add_agent', methods=['POST'])
@master_required
@guarded_route
def add_agent():
    try:
        imie = _clean_name(request.form.get('imie'))
        nazwisko = _clean_name(request.form.get('nazwisko'))
        if not imie or not nazwisko:
            return jsonify({"status": "error", "message": "Imię i nazwisko są wymagane."}), 400
        email = request.form.get('email')
        telefon = request.form.get('telefon')
        licencja = request.form.get('licencja')
        access_level = (request.form.get('access_level') or 'agent').strip() or 'agent'
        if access_level not in ALLOWED_ACCESS_LEVELS:
            return _invalid_access_level_response()
        branch_ids = agents_store.to_int_list(request.form.getlist('branch_ids'))
        role_ids = agents_store.to_int_list(request.form.getlist('role_ids'))
        custom_roles = [x.strip() for x in (request.form.get('custom_roles') or '').split(',') if x.strip()]

        login = f"{imie}.{nazwisko}"
        haslo = generate_initial_password()          # random, never derived from the login; returned ONCE to master, never logged
        hashed_password = generate_password_hash(haslo)
        now_ts = _utc_now()

        with DatabaseConnectionManager('agents') as conn:
            cursor = conn.cursor()

            if login_exists(login):
                return _login_conflict_response()

            new_id = agents_store.next_agent_id(cursor)
            write_inputs(agent_id=new_id, media=False)

            try:
                agents_store.insert_agent(cursor, new_id, login, hashed_password, imie, nazwisko, email, telefon, licencja, access_level, now_ts)
            except sqlite3.IntegrityError as exc:
                # Lost a race with a concurrent add_agent (the UNIQUE index on login is the final arbiter).
                if 'login' in str(exc).lower():
                    return _login_conflict_response()
                raise

            for role_name in custom_roles:
                role_id = agents_store.ensure_role(cursor, role_name)
                if role_id and role_id not in role_ids:
                    role_ids.append(role_id)

            agents_store.sync_agent_branches(cursor, new_id, branch_ids, now_ts)
            agents_store.sync_agent_roles(cursor, new_id, role_ids, now_ts)

            conn.commit()

        get_agents.cache_clear()
        get_branches.cache_clear()
        get_branches_office_data.cache_clear()

        return jsonify({
            "status": "success",
            "message": "Agent dodany.",
            "login": login,
            "password": haslo,
        }), 200

    except ConsistencyError as e:
        return jsonify({"status": "error", "message": str(e)}), 500          # deliberate, user-facing (input lock busy / consistency check)
    except Exception as e:
        return jsonify(_internal_error("agents.add_agent", e)), 500


@investmentmanager_bp.route('/update_agent/<int:agent_id>', methods=['POST'])
@master_required
@guarded_route
def update_agent(agent_id):
    try:
        with DatabaseConnectionManager('agents') as conn:
            previous = agents_store.get_agent_editable_row(conn, agent_id)
        if previous is None:
            return jsonify({'status': 'error', 'message': 'Agent nie istnieje.'}), 404
        imie = request.form.get('imie', previous[0])
        nazwisko = request.form.get('nazwisko', previous[1])
        email = request.form.get('email', previous[2])
        telefon = request.form.get('telefon', previous[3])
        licencja = request.form.get('licencja', previous[4])
        access_level = (request.form.get('access_level', previous[5]) or 'agent').strip() or 'agent'
        if access_level not in ALLOWED_ACCESS_LEVELS:
            return _invalid_access_level_response()
        branch_ids = agents_store.to_int_list(request.form.getlist('branch_ids'))
        role_ids = agents_store.to_int_list(request.form.getlist('role_ids'))
        custom_roles = [x.strip() for x in (request.form.get('custom_roles') or '').split(',') if x.strip()]
        now_ts = _utc_now()

        if agent_export_changed(agent_id, dict(first_name=imie, last_name=nazwisko,
                                              email=email, phone=telefon, license=licencja)):
            write_inputs(agent_id=agent_id, media=False)
        with DatabaseConnectionManager('agents') as conn:
            cursor = conn.cursor()

            agents_store.update_agent_row(cursor, agent_id, imie, nazwisko, email, telefon, licencja, access_level, now_ts)

            for role_name in custom_roles:
                role_id = agents_store.ensure_role(cursor, role_name)
                if role_id and role_id not in role_ids:
                    role_ids.append(role_id)

            agents_store.sync_agent_branches(cursor, agent_id, branch_ids, now_ts)
            agents_store.sync_agent_roles(cursor, agent_id, role_ids, now_ts)

            conn.commit()

        get_agents.cache_clear()
        get_branches.cache_clear()
        get_branches_office_data.cache_clear()
        return jsonify({"status": "success"}), 200

    except ConsistencyError as e:
        return jsonify({"status": "error", "message": str(e)}), 500          # deliberate, user-facing (input lock busy / consistency check)
    except Exception as e:
        return jsonify(_internal_error("agents.update_agent", e)), 500


@investmentmanager_bp.route('/delete_agent/<int:agent_id>', methods=['DELETE'])
@master_required
@guarded_route
def delete_agent(agent_id):
    try:
        write_inputs(agent_id=agent_id, media=False)
        with DatabaseConnectionManager('agents') as conn:
            cursor = conn.cursor()
            agents_store.delete_agent_rows(cursor, agent_id)
            conn.commit()

        get_agents.cache_clear()
        get_branches.cache_clear()
        get_branches_office_data.cache_clear()
        return jsonify({"status": "success"}), 200

    except ConsistencyError as e:
        return jsonify({"status": "error", "message": str(e)}), 500          # deliberate, user-facing (input lock busy / consistency check)
    except Exception as e:
        return jsonify(_internal_error("agents.delete_agent", e)), 500


@investmentmanager_bp.route('/change_password/<int:agent_id>', methods=['POST'])
@master_required
@guarded_route
def change_password(agent_id):
    try:
        new_password = request.form.get('new_password')
        if not new_password:
            return jsonify({"status": "error", "message": "Brak hasła."}), 400

        identity = get_agent_identity(agent_id)
        if identity is None:
            return jsonify({"status": "error", "message": "Agent nie istnieje."}), 404
        policy_error = validate_new_password(new_password, **identity)
        if policy_error:
            return jsonify({"status": "error", "message": policy_error}), 400

        hashed_password = generate_password_hash(new_password)
        with DatabaseConnectionManager('agents') as conn:
            cursor = conn.cursor()
            agents_store.set_agent_password_hash(cursor, agent_id, hashed_password, _utc_now())
            conn.commit()

        if str(agent_id) == str(session.get('user_id')):
            refresh_password_fingerprint(hashed_password)   # master changed their own password: keep this session only

        return jsonify({"status": "success", "message": "Hasło zmienione."}), 200

    except ConsistencyError as e:
        return jsonify({"status": "error", "message": str(e)}), 500          # deliberate, user-facing (input lock busy / consistency check)
    except Exception as e:
        return jsonify(_internal_error("agents.change_password", e)), 500
