from __future__ import annotations

from pathlib import Path

from loki.common.profile import Profile, ProfileRef


def _make_profile(tmp_path: Path) -> Profile:
    return Profile(tmp_path, ProfileRef(platform="playwright", name="default"))


def test_build_playwright_cookies_from_header_uses_config_domain(tmp_path: Path) -> None:
    profile = _make_profile(tmp_path)
    profile.ensure()
    profile.write_config({"cookie_domain": "javdb.com"})
    profile.cookies_path.write_text("a=1; b=2", encoding="utf-8")

    cookies = profile.build_playwright_cookies()

    assert cookies == [
        {"name": "a", "value": "1", "domain": "javdb.com", "path": "/"},
        {"name": "b", "value": "2", "domain": "javdb.com", "path": "/"},
    ]


def test_build_playwright_cookies_from_header_uses_base_url_fallback(tmp_path: Path) -> None:
    profile = _make_profile(tmp_path)
    profile.ensure()
    profile.cookies_path.write_text("sessionid=abc", encoding="utf-8")

    cookies = profile.build_playwright_cookies(base_url="https://www.tiktok.com/@foo")

    assert cookies == [
        {"name": "sessionid", "value": "abc", "url": "https://www.tiktok.com/"},
    ]


def test_build_playwright_cookies_from_netscape_file(tmp_path: Path) -> None:
    profile = _make_profile(tmp_path)
    profile.ensure()
    profile.cookies_path.write_text(
        "# Netscape HTTP Cookie File\n"
        ".javdb.com\tTRUE\t/\tFALSE\t2147483647\tover18\t1\n",
        encoding="utf-8",
    )

    cookies = profile.build_playwright_cookies()

    assert len(cookies) == 1
    assert cookies[0]["name"] == "over18"
    assert cookies[0]["value"] == "1"
    assert cookies[0]["domain"] == ".javdb.com"
    assert cookies[0]["path"] == "/"
    assert cookies[0]["expires"] == 2147483647.0
