"""Shared agent/branch reads; each cache has one owner."""
from functools import lru_cache
from modules.classes import DatabaseConnectionManager


@lru_cache(maxsize=128)
def get_agents():
    with DatabaseConnectionManager("agents") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            SELECT first_name, last_name, email, phone, license, id
            FROM agents_v2
            WHERE id != 100
              AND is_active = 1
        """)
        return cursor.fetchall()


@lru_cache(maxsize=128)
def get_branches():
    with DatabaseConnectionManager("agents") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            SELECT ab.agent_id, b.name
            FROM agent_branches_v2 ab
            JOIN branches_v2 b ON b.id = ab.branch_id
            WHERE b.is_active = 1
        """)
        return cursor.fetchall()


@lru_cache(maxsize=128)
def get_branches_office_data():
    with DatabaseConnectionManager("agents") as conn:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT name, COALESCE(title, ''), COALESCE(image_url, ''), COALESCE(info1, ''), COALESCE(info2, '')
            FROM branches_v2
            WHERE is_active = 1
            """
        )
        rows = cursor.fetchall()

    return {
        row[0]: {
            "key": row[0],
            "title": row[1] or f"Oddział {row[0]}",
            "image": row[2],
            "info1": row[3],
            "info2": row[4],
        }
        for row in rows
        if row[0]
    }
