"""Local read-only replacement for the active Streamlit/SSH gateway."""
from . import runtime_paths
from .portals.domain import OfferRecord, LocationRecord, AgentRecord


def _row(path, sql, identifier):
    with runtime_paths.read_connection(path) as conn:
        return conn.execute(sql, (identifier,)).fetchone()


def _legacy_text_row(row):
    # The SSH gateway strips the entire pipe-delimited sqlite3 result before
    # splitting it. Interior cells retain whitespace; only result boundaries
    # are trimmed. Keep empty/NULL cells and the original delimiter semantics.
    return "|".join(str(value) if value is not None else "" for value in row).strip().split("|")


def get_agent_data(agent_id):
    # Preserve the original positional nine-column contract. No values are logged.
    row = _row(runtime_paths.agents_db_path(), """
        SELECT id, login, password_hash, access_level, first_name, last_name,
               email, phone, license
        FROM agents_v2 WHERE id = ? AND is_active = 1
    """, agent_id)
    return _legacy_text_row(row) if row else [""]


class LocalExportGateway:
    def get_offer_data(self, offer_id):
        row = _row(runtime_paths.idb_db_path(), "SELECT * FROM EstateData WHERE ID = ?", offer_id)
        if row is None:
            raise ValueError(f"Offer not found: {offer_id}")
        return OfferRecord.from_row(_legacy_text_row(row))

    def get_location_data(self, offer_id):
        row = _row(runtime_paths.idb_db_path(), "SELECT * FROM Localization WHERE ID = ?", offer_id)
        if row is None:
            raise ValueError(f"Localization not found for offer: {offer_id}")
        return LocationRecord.from_row(_legacy_text_row(row))

    def get_agent_data(self, agent_id):
        row = get_agent_data(agent_id)
        if row == [""]:
            raise ValueError(f"Agent not found: {agent_id}")
        return AgentRecord.from_row(row)

    def get_description(self, offer_id):
        path = runtime_paths.checked_path(runtime_paths.local_offer_dir(offer_id) / f"description_{offer_id}.md")
        return path.read_bytes().decode("utf-8") if path.is_file() else None

    def count_photos(self, offer_id):
        from .export_packaging import count_photos
        return count_photos(offer_id)
