"""Tests para browser_profile_open.

browser_profile_open compone browser_profile_show (lectura de metadata) y lanza
Chromium via systemd-run. Aqui se mockea browser_profile_show (ligado en el modulo por
el `from browser.browser_profile_show import browser_profile_show`) y se usa dry_run=True
para NO abrir navegador. Se valida el comando construido en los dos casos clave:
- user_data_dir vacio -> NO se pasa --user-data-dir (lo hereda el wrapper chromium-cdp).
- user_data_dir custom -> SI se pasa --user-data-dir explicito.
"""

import os
import sys

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

import browser.browser_profile_open as bpo
from browser.browser_profile_open import browser_profile_open


def _show_ret(user_data_dir=""):
    """Construye una respuesta ok de browser_profile_show con cuentas."""
    return {
        "status": "ok",
        "profile": {"profile_dir": "Profile 1", "user_data_dir": user_data_dir,
                    "label": "Maria", "status": "active"},
        "accounts": [
            {"id": "Profile 1:gmail:maria@example.com", "service": "gmail",
             "identity": "maria@example.com", "secret_ref": "pass show osint/p1/gmail",
             "role": "primary", "status": "active", "notes": ""},
        ],
    }


def test_dry_run_default_user_data_dir_no_pasa_user_data_dir(monkeypatch):
    # user_data_dir vacio en la fila -> default del wrapper -> NO --user-data-dir.
    monkeypatch.setattr(bpo, "browser_profile_show", lambda pd, base_url="": _show_ret(""))

    res = browser_profile_open("Profile 1", url="https://mail.google.com", dry_run=True)

    assert res["status"] == "ok"
    assert res["profile_dir"] == "Profile 1"
    cmd = res["cmd"]
    # Lanzamiento aislado via systemd-run --user --scope --.
    assert cmd[:5] == ["systemd-run", "--user", "--scope", "--", "chromium"]
    assert '--profile-directory=Profile 1' in cmd
    # Caso default: NO debe aparecer --user-data-dir (lo inyecta el wrapper).
    assert not any(a.startswith("--user-data-dir=") for a in cmd)
    # La URL va al final.
    assert cmd[-1] == "https://mail.google.com"
    # Las cuentas se exponen con su secret_ref (referencia, nunca el password).
    assert res["accounts"][0]["secret_ref"] == "pass show osint/p1/gmail"
    assert res["accounts"][0]["service"] == "gmail"


def test_dry_run_custom_user_data_dir_pasa_flag_explicito(monkeypatch):
    custom = "/mnt/data/chromium-osint"
    monkeypatch.setattr(bpo, "browser_profile_show", lambda pd, base_url="": _show_ret(custom))

    res = browser_profile_open("Profile 1", dry_run=True)

    assert res["status"] == "ok"
    cmd = res["cmd"]
    # Caso custom: SI debe aparecer --user-data-dir explicito con el dir de la fila.
    assert f"--user-data-dir={custom}" in cmd
    assert '--profile-directory=Profile 1' in cmd
    # Sin url -> el ultimo arg NO es una URL.
    assert not cmd[-1].startswith("http")


def test_dry_run_user_data_dir_default_explicito_no_se_pasa(monkeypatch):
    # Si la fila trae EXACTAMENTE el default (con ~), tampoco debe pasarse --user-data-dir.
    monkeypatch.setattr(
        bpo, "browser_profile_show",
        lambda pd, base_url="": _show_ret("~/.config/chromium-cdp"),
    )

    res = browser_profile_open("Profile 1", dry_run=True)

    assert res["status"] == "ok"
    cmd = res["cmd"]
    assert not any(a.startswith("--user-data-dir=") for a in cmd)


def test_error_perfil_no_existe_propaga_sin_lanzar(monkeypatch):
    err = {"status": "error", "error": "perfil no encontrado: fantasma"}
    monkeypatch.setattr(bpo, "browser_profile_show", lambda pd, base_url="": err)

    res = browser_profile_open("fantasma", dry_run=True)

    assert res["status"] == "error"
    assert "no encontrado" in res["error"]
    # No hay cmd ni launched cuando el perfil no existe.
    assert "cmd" not in res
    assert "launched" not in res
