"""Tests for user profile loading."""

from pathlib import Path

from fliiq.runtime.config import load_user_profile


def test_load_user_profile_missing(monkeypatch, tmp_path):
    """Returns empty dict when user.yaml doesn't exist."""
    monkeypatch.setattr("fliiq.runtime.config.GLOBAL_DIR", tmp_path / "nonexistent")
    assert load_user_profile() == {}


def test_load_user_profile_valid(monkeypatch, tmp_path):
    """Parses a valid user.yaml."""
    fliiq_dir = tmp_path / ".fliiq"
    fliiq_dir.mkdir()
    (fliiq_dir / "user.yaml").write_text(
        "name: Test User\n"
        "emails:\n"
        "  - address: test@gmail.com\n"
        "    label: personal\n"
        "timezone: America/New_York\n"
    )
    monkeypatch.setattr("fliiq.runtime.config.GLOBAL_DIR", fliiq_dir)
    profile = load_user_profile()
    assert profile["name"] == "Test User"
    assert profile["emails"][0]["address"] == "test@gmail.com"
    assert profile["timezone"] == "America/New_York"


def test_load_user_profile_commented_out(monkeypatch, tmp_path):
    """Returns empty dict when file has only comments."""
    fliiq_dir = tmp_path / ".fliiq"
    fliiq_dir.mkdir()
    (fliiq_dir / "user.yaml").write_text(
        "# name: Your Name\n"
        "# email: your@email.com\n"
    )
    monkeypatch.setattr("fliiq.runtime.config.GLOBAL_DIR", fliiq_dir)
    # All commented = yaml parses as None → returns {}
    assert load_user_profile() == {}


def test_load_user_profile_malformed(monkeypatch, tmp_path):
    """Returns empty dict on malformed YAML."""
    fliiq_dir = tmp_path / ".fliiq"
    fliiq_dir.mkdir()
    (fliiq_dir / "user.yaml").write_text("{{{{invalid yaml")
    monkeypatch.setattr("fliiq.runtime.config.GLOBAL_DIR", fliiq_dir)
    assert load_user_profile() == {}


def test_load_user_profile_multiple_emails(monkeypatch, tmp_path):
    """Handles multiple email entries."""
    fliiq_dir = tmp_path / ".fliiq"
    fliiq_dir.mkdir()
    (fliiq_dir / "user.yaml").write_text(
        "name: Andy Chan\n"
        "emails:\n"
        "  - address: personal@gmail.com\n"
        "    label: personal\n"
        "  - address: work@gmail.com\n"
        "    label: work\n"
    )
    monkeypatch.setattr("fliiq.runtime.config.GLOBAL_DIR", fliiq_dir)
    profile = load_user_profile()
    assert len(profile["emails"]) == 2
    assert profile["emails"][1]["label"] == "work"
