"""Tests para browser_profile_list.

Se mockea el helper `query` (ligado en el modulo por el `from browser._osint_db_client
import query`) para validar el armado del SELECT (filtro por status) y el mapeo
columns->rows a lista de dicts. NO toca el service real.
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

import browser.browser_profile_list as bpl
from browser.browser_profile_list import browser_profile_list


class _QuerySpy:
    def __init__(self, ret):
        self.calls = []  # lista de (sql, params)
        self.ret = ret

    def __call__(self, base_url, sql, params=None, max_rows=None):
        self.calls.append((sql, params))
        return self.ret


def test_golden_lista_perfiles_mapea_columns_a_dicts(monkeypatch):
    ret = {
        "status": "ok",
        "columns": ["profile_dir", "label", "persona", "purpose", "status",
                    "note_path", "n_accounts"],
        "rows": [
            ["Profile 1", "Maria", "maria_fake", "rastreo", "active", "notes/p1.md", 2],
            ["osint_01", "", "", "", "active", "", 0],
        ],
        "row_count": 2,
    }
    spy = _QuerySpy(ret)
    monkeypatch.setattr(bpl, "query", spy)

    res = browser_profile_list()

    assert res["status"] == "ok"
    assert len(res["profiles"]) == 2
    assert res["profiles"][0] == {
        "profile_dir": "Profile 1", "label": "Maria", "persona": "maria_fake",
        "purpose": "rastreo", "status": "active", "note_path": "notes/p1.md",
        "n_accounts": 2,
    }
    assert res["profiles"][1]["n_accounts"] == 0
    # Sin filtro: no debe haber WHERE y params vacio.
    sql, params = spy.calls[0]
    assert "WHERE" not in sql
    assert params == []
    assert "LEFT JOIN" in sql


def test_edge_filtro_status_agrega_where_y_param(monkeypatch):
    spy = _QuerySpy({"status": "ok", "columns": [], "rows": [], "row_count": 0})
    monkeypatch.setattr(bpl, "query", spy)

    res = browser_profile_list(status="archived")

    assert res["status"] == "ok"
    assert res["profiles"] == []
    sql, params = spy.calls[0]
    assert "WHERE p.status = ?" in sql
    assert params == ["archived"]


def test_error_query_falla_devuelve_status_error(monkeypatch):
    spy = _QuerySpy({"status": "error", "error": "service osint_db inaccesible en ..."})
    monkeypatch.setattr(bpl, "query", spy)

    res = browser_profile_list()

    assert res["status"] == "error"
    assert "inaccesible" in res["error"]
