"""Owner of the SQL on the agents directory: `agents_v2`, `branches_v2`, `roles_v2`, `agent_branches_v2`, `agent_roles_v2` (agents.db).

Every statement of the CRM agents administration (routes/agents.py), of the own-profile update (routes/dashboard.py) and of the login lookup
(middleware/auth.py) lives here, moved verbatim: SQL, parameters, order and NULL handling are exactly those the routes used before.

What this module does NOT own: HTTP, permissions, passwords and their policy, sessions, export-input protocol (`write_inputs`) and the
connection / transaction boundary. Callers keep opening the connection (`DatabaseConnectionManager('agents')`), commit explicitly and pass
the cursor (or the connection - both offer `execute`) to these functions, so one logical change is still ONE transaction decided by the
caller, and an early return or an exception still ends the connection without a commit, as before.

Reads that serve the public Website live in `modules/core/agent_queries.py` (frozen contract) and are not touched here.
"""


# ------------------------------------------------------------------------------------------------ small value helpers
def to_int_list(values):
    """Integers found in `values` (anything that does not parse is skipped), in order."""
    result = []
    for value in values:
        try:
            parsed = int(str(value).strip())
            result.append(parsed)
        except Exception:
            continue
    return result


def _normalize_slug(value: str, default_value: str) -> str:
    text = (value or "").strip().lower()
    replacements = {
        "ą": "a",
        "ć": "c",
        "ę": "e",
        "ł": "l",
        "ń": "n",
        "ó": "o",
        "ś": "s",
        "ż": "z",
        "ź": "z",
    }
    for src, dst in replacements.items():
        text = text.replace(src, dst)

    parts = []
    for ch in text:
        if ch.isalnum():
            parts.append(ch)
        elif ch in {" ", "-", "_", "/"}:
            parts.append("-")

    code = "".join(parts).strip("-")
    while "--" in code:
        code = code.replace("--", "-")
    return code or default_value


def _normalize_branch_code(value: str) -> str:
    return _normalize_slug(value, "oddzial")


def _normalize_role_code(value: str) -> str:
    return _normalize_slug(value, "rola")


# ------------------------------------------------------------------------------------------------ roles
def find_role_id_by_name(cursor, name):
    """Row (id,) of the role whose name equals `name` ignoring (ASCII) case, or None."""
    return cursor.execute(
        "SELECT id FROM roles_v2 WHERE lower(name) = lower(?)",
        (name,),
    ).fetchone()


def ensure_role(cursor, role_name: str):
    """Id of the role named `role_name` (created with a unique slug code when it does not exist yet); None for a blank name."""
    clean = (role_name or "").strip()
    if not clean:
        return None

    row = find_role_id_by_name(cursor, clean)
    if row:
        return row[0]

    base_code = _normalize_role_code(clean)
    code = base_code
    suffix = 2
    while cursor.execute("SELECT 1 FROM roles_v2 WHERE code = ?", (code,)).fetchone():
        code = f"{base_code}-{suffix}"
        suffix += 1

    cursor.execute(
        """
        INSERT INTO roles_v2 (code, name, description, is_active)
        VALUES (?, ?, '', 1)
        """,
        (code, clean),
    )
    return cursor.lastrowid


def get_role_row(cursor, role_id):
    return cursor.execute("SELECT id FROM roles_v2 WHERE id = ?", (role_id,)).fetchone()


def find_other_role_with_name(cursor, role_name, role_id):
    return cursor.execute(
        "SELECT id FROM roles_v2 WHERE lower(name) = lower(?) AND id != ?",
        (role_name, role_id),
    ).fetchone()


def update_role(cursor, role_id, role_name):
    """Rename the role and recompute its unique slug code (ignoring the role itself)."""
    base_code = _normalize_role_code(role_name)
    code = base_code
    suffix = 2
    while cursor.execute(
        "SELECT 1 FROM roles_v2 WHERE code = ? AND id != ?",
        (code, role_id),
    ).fetchone():
        code = f"{base_code}-{suffix}"
        suffix += 1

    cursor.execute(
        "UPDATE roles_v2 SET name = ?, code = ? WHERE id = ?",
        (role_name, code, role_id),
    )


def count_role_assignments(cursor, role_id):
    return cursor.execute(
        "SELECT COUNT(*) FROM agent_roles_v2 WHERE role_id = ?",
        (role_id,),
    ).fetchone()[0]


def delete_role(cursor, role_id):
    cursor.execute("DELETE FROM roles_v2 WHERE id = ?", (role_id,))


def get_roles_payload(cursor):
    rows = cursor.execute(
        """
        SELECT id, code, name, COALESCE(description, ''), is_active
        FROM roles_v2
        ORDER BY name
        """
    ).fetchall()
    return [
        {
            "id": row[0],
            "code": row[1],
            "name": row[2],
            "description": row[3],
            "is_active": int(row[4] or 0),
        }
        for row in rows
    ]


# ------------------------------------------------------------------------------------------------ branches
def find_branch_id_by_name(cursor, name):
    return cursor.execute("SELECT id FROM branches_v2 WHERE lower(name) = lower(?)", (name,)).fetchone()


def find_other_branch_with_name(cursor, name, branch_id):
    return cursor.execute(
        "SELECT id FROM branches_v2 WHERE lower(name) = lower(?) AND id != ?",
        (name, branch_id),
    ).fetchone()


def insert_branch(cursor, name, title, info1, info2, image_url, now_ts):
    """Create the branch with a unique slug code derived from its name."""
    base_code = _normalize_branch_code(name)
    code = base_code
    suffix = 2
    while cursor.execute("SELECT 1 FROM branches_v2 WHERE code = ?", (code,)).fetchone():
        code = f"{base_code}-{suffix}"
        suffix += 1

    cursor.execute(
        """
        INSERT INTO branches_v2 (code, name, title, image_url, info1, info2, is_active, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)
        """,
        (code, name, title, image_url, info1, info2, now_ts, now_ts),
    )


def update_branch(cursor, branch_id, name, title, info1, info2, image_url, now_ts):
    """Update the branch and recompute its unique slug code (ignoring the branch itself)."""
    base_code = _normalize_branch_code(name)
    code = base_code
    suffix = 2
    while cursor.execute("SELECT 1 FROM branches_v2 WHERE code = ? AND id != ?", (code, branch_id)).fetchone():
        code = f"{base_code}-{suffix}"
        suffix += 1

    cursor.execute(
        """
        UPDATE branches_v2
        SET code = ?, name = ?, title = ?, image_url = ?, info1 = ?, info2 = ?, updated_at = ?
        WHERE id = ?
        """,
        (code, name, title, image_url, info1, info2, now_ts, branch_id),
    )


def count_branch_assignments(cursor, branch_id):
    return cursor.execute(
        "SELECT COUNT(*) FROM agent_branches_v2 WHERE branch_id = ?",
        (branch_id,),
    ).fetchone()[0]


def delete_branch(cursor, branch_id):
    cursor.execute("DELETE FROM branches_v2 WHERE id = ?", (branch_id,))


def get_branches_payload(cursor):
    rows = cursor.execute(
        """
        SELECT id, code, name, COALESCE(title, ''), COALESCE(info1, ''), COALESCE(info2, ''), COALESCE(image_url, ''), is_active
        FROM branches_v2
        ORDER BY name
        """
    ).fetchall()
    return [
        {
            "id": row[0],
            "code": row[1],
            "name": row[2],
            "title": row[3],
            "info1": row[4],
            "info2": row[5],
            "image_url": row[6],
            "is_active": int(row[7] or 0),
        }
        for row in rows
    ]


# ------------------------------------------------------------------------------------------------ agents
def get_agents_payload(cursor):
    rows = cursor.execute(
        """
        SELECT
            a.id,
            a.first_name,
            a.last_name,
            COALESCE(a.email, ''),
            COALESCE(a.phone, ''),
            COALESCE(a.license, ''),
            COALESCE(a.access_level, ''),
            COALESCE(GROUP_CONCAT(DISTINCT b.id), ''),
            COALESCE(GROUP_CONCAT(DISTINCT b.name), ''),
            COALESCE(GROUP_CONCAT(DISTINCT r.id), ''),
            COALESCE(GROUP_CONCAT(DISTINCT r.name), '')
        FROM agents_v2 a
        LEFT JOIN agent_branches_v2 ab ON ab.agent_id = a.id
        LEFT JOIN branches_v2 b ON b.id = ab.branch_id
        LEFT JOIN agent_roles_v2 ar ON ar.agent_id = a.id
        LEFT JOIN roles_v2 r ON r.id = ar.role_id
        WHERE a.is_active = 1
          AND a.id != 100
        GROUP BY a.id, a.first_name, a.last_name, a.email, a.phone, a.license, a.access_level
        ORDER BY a.last_name, a.first_name
        """
    ).fetchall()

    agents = []
    for row in rows:
        branch_ids = to_int_list([x for x in row[7].split(',') if x])
        branch_names = [x.strip() for x in row[8].split(',') if x.strip()]
        role_ids = to_int_list([x for x in row[9].split(',') if x])
        role_names = [x.strip() for x in row[10].split(',') if x.strip()]
        primary_branch = branch_names[0] if branch_names else "—"

        agents.append(
            {
                "id": row[0],
                "imie": row[1],
                "nazwisko": row[2],
                "email": row[3],
                "telefon": row[4],
                "licencja": row[5],
                "access_level": row[6],
                "obszar": primary_branch,
                "branch_ids": branch_ids,
                "branch_names": branch_names,
                "role_ids": role_ids,
                "roles": role_names,
            }
        )
    return agents


def next_agent_id(cursor):
    """MAX(id) + 1 (1 for an empty table), read on the caller's transaction."""
    cursor.execute("SELECT MAX(id) FROM agents_v2")
    max_id = cursor.fetchone()[0] or 0
    return max_id + 1


def insert_agent(cursor, new_id, login, hashed_password, first_name, last_name, email, phone, licence, access_level, now_ts):
    cursor.execute(
        """
        INSERT INTO agents_v2 (
            id, login, password_hash, first_name, last_name, email, phone, license,
            access_level, is_active, created_at, updated_at
        )
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)
        """,
        (new_id, login, hashed_password, first_name, last_name, email, phone, licence, access_level, now_ts, now_ts),
    )


def get_agent_editable_row(conn, agent_id):
    """Row (first_name, last_name, email, phone, license, access_level) of the agent, or None."""
    return conn.execute('SELECT first_name,last_name,email,phone,license,access_level FROM agents_v2 WHERE id=?', (agent_id,)).fetchone()


def update_agent_row(cursor, agent_id, first_name, last_name, email, phone, licence, access_level, now_ts):
    cursor.execute(
        """
        UPDATE agents_v2
        SET first_name = ?, last_name = ?, email = ?, phone = ?, license = ?, access_level = ?, updated_at = ?
        WHERE id = ?
        """,
        (first_name, last_name, email, phone, licence, access_level, now_ts, agent_id),
    )


def sync_agent_branches(cursor, agent_id: int, branch_ids: list[int], now_ts: str):
    cursor.execute("DELETE FROM agent_branches_v2 WHERE agent_id = ?", (agent_id,))
    for idx, branch_id in enumerate(branch_ids):
        cursor.execute(
            """
            INSERT INTO agent_branches_v2 (agent_id, branch_id, is_primary, created_at)
            VALUES (?, ?, ?, ?)
            """,
            (agent_id, branch_id, 1 if idx == 0 else 0, now_ts),
        )


def sync_agent_roles(cursor, agent_id: int, role_ids: list[int], now_ts: str):
    cursor.execute("DELETE FROM agent_roles_v2 WHERE agent_id = ?", (agent_id,))
    for role_id in role_ids:
        cursor.execute(
            """
            INSERT INTO agent_roles_v2 (agent_id, role_id, created_at)
            VALUES (?, ?, ?)
            """,
            (agent_id, role_id, now_ts),
        )


def delete_agent_rows(cursor, agent_id):
    """Remove the agent's role and branch assignments, then the agent (in this order)."""
    cursor.execute("DELETE FROM agent_roles_v2 WHERE agent_id = ?", (agent_id,))
    cursor.execute("DELETE FROM agent_branches_v2 WHERE agent_id = ?", (agent_id,))
    cursor.execute("DELETE FROM agents_v2 WHERE id = ?", (agent_id,))


def set_agent_password_hash(cursor, agent_id, hashed_password, now_ts):
    cursor.execute(
        "UPDATE agents_v2 SET password_hash = ?, updated_at = ? WHERE id = ?",
        (hashed_password, now_ts, agent_id),
    )


# ------------------------------------------------------------------------------------------------ own profile (dashboard.update_profile)
def get_agent_contact_row(conn, agent_id):
    """Row (email, phone, license) of the agent, or None."""
    return conn.execute('SELECT email,phone,license FROM agents_v2 WHERE id=?', (agent_id,)).fetchone()


def update_agent_contact(cursor, agent_id, email, phone, licence, now_ts):
    cursor.execute("""
        UPDATE agents_v2
        SET email = ?, phone = ?, license = ?, updated_at = ?
        WHERE id = ?
    """, (
        email,
        phone,
        licence,
        now_ts,
        agent_id
    ))


def get_agent_password_row(cursor, agent_id):
    """Row (password_hash, login, first_name, last_name) of the agent, or None (fetched on the caller's cursor)."""
    cursor.execute("SELECT password_hash, login, first_name, last_name FROM agents_v2 WHERE id = ?", (agent_id,))
    return cursor.fetchone()


# ------------------------------------------------------------------------------------------------ login (middleware/auth.py)
def get_active_agent_for_login(cursor, login):
    """Row (id, login, first_name, password_hash, access_level, last_name, email, phone, license) of the ACTIVE agent with exactly this login."""
    cursor.execute("""
        SELECT id, login, first_name, password_hash, access_level, last_name, email, phone, license
        FROM agents_v2
        WHERE login = ?
          AND is_active = 1
    """, (login,))
    return cursor.fetchone()
