"""site_bookmarks：URL 规范、YAML 读写、CRUD（不联网）。"""

from __future__ import annotations

import asyncio
from pathlib import Path

import pytest

from aicd.tools import site_bookmarks as sb


def test_normalize_site_root_only() -> None:
    u, e = sb.normalize_site_url("https://github.com/foo/bar")
    assert u is None and e and "路径" in e
    u2, e2 = sb.normalize_site_url("github.com", strict_site_root=True)
    assert u2 == "https://github.com/" and e2 is None


def test_normalize_single_segment_when_allowed() -> None:
    u, e = sb.normalize_site_url(
        "https://example.com/docs",
        strict_site_root=False,
        allow_single_path_segment=True,
    )
    assert u == "https://example.com/docs" and e is None


def test_add_list_remove_without_fetch(tmp_path: Path) -> None:
    data = tmp_path / "data"

    async def _run() -> None:
        return await sb.add_entry(
            data,
            url="https://example.org",
            display_name="Ex",
            tags=["test"],
            notes="n",
            fetch_summary=False,
        )

    r = asyncio.run(_run())
    assert r["ok"] is True
    assert r["entry"]["id"]
    lst = sb.list_entries(data)
    assert lst["count"] == 1
    rm = sb.remove_entry(data, entry_id=r["entry"]["id"], url=None)
    assert rm["ok"] is True
    lst2 = sb.list_entries(data)
    assert lst2["count"] == 0


def test_ensure_file_creates_skeleton(tmp_path: Path) -> None:
    data = tmp_path / "d"
    sb.ensure_site_bookmarks_file(data)
    p = sb.site_bookmarks_path(data)
    assert p.is_file()
    assert "entries" in p.read_text(encoding="utf-8")


def test_duplicate_add_rejected(tmp_path: Path) -> None:
    data = tmp_path / "data2"

    async def _run() -> None:
        await sb.add_entry(
            data, url="https://dup.test/", fetch_summary=False
        )
        r2 = await sb.add_entry(
            data, url="https://dup.test", fetch_summary=False
        )
        assert r2["ok"] is False

    asyncio.run(_run())
