import pytest
from uuid import uuid4
from datetime import datetime, timezone
from tests.conftest import BASE_URL, assert_share_copies
from devplacepy.database import get_table
from devplacepy.utils import make_combined_slug


def test_news_detail_share_button(page, news_article):
    slug = news_article.get("slug") or news_article["uid"]
    page.goto(f"{BASE_URL}/news/{slug}", wait_until="domcontentloaded")
    assert_share_copies(page, "/news/")


def seed_news():
    news_table = get_table("news")
    for i in range(3):
        eid = f"test_news_{i}"
        if news_table.find_one(external_id=eid):
            continue
        uid = str(uuid4())
        title = f"News Test Article {i}"
        slug = make_combined_slug(title, uid)
        news_table.insert({
            "uid": uid, "slug": slug, "title": title,
            "external_id": eid, "grade": 8 + i,
            "status": "published", "show_on_landing": 1,
            "source_name": "TestSource",
            "synced_at": datetime.now(timezone.utc).isoformat(),
            "description": f"Description for test article {i}.",
        })


@pytest.fixture
def news_article(app_server):
    seed_news()
    article = get_table("news").find_one(order_by=["-synced_at"])
    return article


def test_news_listing_loads(page, app_server):
    seed_news()
    page.goto(f"{BASE_URL}/news", wait_until="domcontentloaded")
    assert page.is_visible("text=Developer News")
    assert page.is_visible("text=News Test Article")


def test_news_listing_authenticated(alice):
    page, _ = alice
    seed_news()
    page.goto(f"{BASE_URL}/news", wait_until="domcontentloaded")
    assert page.is_visible("text=Developer News")


def test_news_detail_loads(page, news_article):
    slug = news_article.get("slug") or news_article["uid"]
    page.goto(f"{BASE_URL}/news/{slug}", wait_until="domcontentloaded")
    assert page.is_visible("text=News Test Article")
    assert page.is_visible("text=Comments")


def test_news_detail_404(page, app_server):
    page.goto(f"{BASE_URL}/news/nonexistent-article", wait_until="domcontentloaded")
    assert page.is_visible("text=not found", timeout=5000)


def test_news_comment(alice, news_article):
    page, _ = alice
    slug = news_article.get("slug") or news_article["uid"]
    page.goto(f"{BASE_URL}/news/{slug}", wait_until="domcontentloaded")
    page.fill("textarea[name='content']", "Test comment on news article")
    page.click("button:has-text('Post')")
    page.wait_for_url(f"{BASE_URL}/news/{slug}", wait_until="domcontentloaded")
    assert page.is_visible("text=Test comment on news article")


def test_news_detail_guest(page, news_article):
    slug = news_article.get("slug") or news_article["uid"]
    page.goto(f"{BASE_URL}/news/{slug}", wait_until="domcontentloaded")
    assert page.is_visible("text=News Test Article")
    assert page.is_visible("text=Comments")
    assert page.is_visible("text=Read on TestSource")

