# retoor <retoor@molodetz.nl>

from uuid import uuid4
from datetime import datetime, timezone
from tests.conftest import BASE_URL
from devplacepy.database import get_table
import requests
def _seed_news_seo():
    from datetime import datetime, timezone
    from devplacepy.database import get_table
    from devplacepy.utils import generate_uid, make_combined_slug

    uid = generate_uid()
    title = f"SEO Test News Article {uid.split('-')[-1]}"
    slug = make_combined_slug(title, uid)
    get_table("news").insert(
        {
            "deleted_at": None,
            "deleted_by": None,
            "uid": uid,
            "slug": slug,
            "title": title,
            "description": "A seeded news article for SEO tests.",
            "content": "Body content for the seeded article.",
            "url": "https://example.com/article",
            "source_name": "ExampleSource",
            "status": "published",
            "synced_at": datetime.now(timezone.utc).isoformat(),
            "show_on_landing": 0,
            "grade": 8,
        }
    )
    return slug, uid
def _seed_owner():
    from datetime import datetime, timezone
    from uuid import uuid4
    from devplacepy.database import get_table

    uid = str(uuid4())
    get_table("users").insert(
        {
            "uid": uid,
            "username": f"seo_{uid[:8]}",
            "terms_version": "1",
            "email": f"{uid[:8]}@seo.test",
            "password_hash": "x",
            "role": "Member",
            "is_active": True,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    return uid
def _seed_post_seo(image=None):
    from datetime import datetime, timezone
    from uuid import uuid4
    from devplacepy.database import get_table
    from devplacepy.utils import make_combined_slug

    owner = _seed_owner()
    uid = str(uuid4())
    slug = make_combined_slug("SEO Detail Post", uid)
    get_table("posts").insert(
        {
            "deleted_at": None,
            "deleted_by": None,
            "uid": uid,
            "user_uid": owner,
            "slug": slug,
            "title": "SEO Detail Post",
            "content": "Body text for the SEO detail post.",
            "topic": "general",
            "project_uid": None,
            "image": image,
            "stars": 0,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    return slug, uid
def _seed_gist():
    from datetime import datetime, timezone
    from uuid import uuid4
    from devplacepy.database import get_table
    from devplacepy.utils import make_combined_slug

    owner = _seed_owner()
    uid = str(uuid4())
    slug = make_combined_slug("SEO Detail Gist", uid)
    get_table("gists").insert(
        {
            "deleted_at": None,
            "deleted_by": None,
            "uid": uid,
            "user_uid": owner,
            "slug": slug,
            "title": "SEO Detail Gist",
            "description": "Gist description for SEO tests.",
            "source_code": "print('seo')",
            "language": "python",
            "stars": 0,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    return slug, uid
def _seed_project():
    from datetime import datetime, timezone
    from uuid import uuid4
    from devplacepy.database import get_table
    from devplacepy.utils import make_combined_slug

    owner = _seed_owner()
    uid = str(uuid4())
    slug = make_combined_slug("SEO Detail Project", uid)
    get_table("projects").insert(
        {
            "deleted_at": None,
            "deleted_by": None,
            "uid": uid,
            "user_uid": owner,
            "slug": slug,
            "title": "SEO Detail Project",
            "description": "Project description for SEO tests.",
            "project_type": "software",
            "platforms": "Linux",
            "status": "Released",
            "stars": 0,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    return slug, uid
def _seed_news_image(news_uid):
    from devplacepy.database import get_table

    get_table("news_images").insert(
        {
            "deleted_at": None,
            "deleted_by": None,
            "news_uid": news_uid,
            "url": "https://example.com/seo-news-image.jpg",
        }
    )
def _seed_feed_posts(count):
    from datetime import datetime, timezone, timedelta
    from uuid import uuid4
    from devplacepy.database import get_table
    from devplacepy.utils import make_combined_slug

    owner = _seed_owner()
    topic = f"seopag{owner[:8]}"
    base = datetime(2026, 1, 1, tzinfo=timezone.utc)
    posts = get_table("posts")
    for i in range(count):
        uid = str(uuid4())
        posts.insert(
            {
                "deleted_at": None,
                "deleted_by": None,
                "uid": uid,
                "user_uid": owner,
                "slug": make_combined_slug(f"seo pag {i}", uid),
                "title": None,
                "content": f"seo pag post {i}",
                "topic": topic,
                "project_uid": None,
                "image": None,
                "stars": 0,
                "created_at": (base - timedelta(seconds=i)).isoformat(),
            }
        )
    return topic


def test_landing_page_loads(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    assert "DevPlace" in page.title()
    assert page.is_visible("text=Devplace.net")
    assert page.is_visible("text=The Developer Social Network")


def test_landing_tagline(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    tagline = page.text_content("p")
    assert "Track industry shifts" in tagline


def test_landing_join_button(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    btn = page.locator("text=Join DevPlace Free")
    assert btn.is_visible()
    assert btn.get_attribute("href") == "/auth/signup"


def test_landing_features(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    features = [
        "100% Free Forever",
        "Zero Ads",
        "No Gatekeeping",
        "No Payments",
    ]
    for feature in features:
        assert page.is_visible(f"text={feature}")


def test_landing_nav_links(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    assert page.is_visible("a:has-text('Home')")
    assert page.is_visible("a:has-text('News')")
    assert page.is_visible("a:has-text('Projects')")
    assert page.is_visible("a:has-text('Login')")
    assert page.is_visible("a:has-text('Sign Up')")


def test_landing_footer_links(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    assert page.is_visible("a:has-text('Issue Report')")


def test_landing_hero_present(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    assert page.is_visible("text=Log In")
    assert page.is_visible("text=Join DevPlace Free")
    assert page.is_visible("text=Devplace.net")


def test_landing_news_section(page, app_server):
    uid = str(uuid4())
    get_table("news").insert(
        {
            "deleted_at": None,
            "deleted_by": None,
            "uid": uid,
            "slug": f"landing-news-{uid[:8]}",
            "title": f"Landing News {uid[:8]}",
            "external_id": f"landing_test_{uid[:8]}",
            "grade": 8,
            "status": "published",
            "show_on_landing": 1,
            "source_name": "LandingTest",
            "synced_at": datetime.now(timezone.utc).isoformat(),
            "description": "Seeded article so the landing news section renders.",
        }
    )
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    page.locator("text=Developer News").wait_for(state="visible", timeout=5000)
    cards = page.locator(".news-card-title a")
    assert cards.count() > 0, "No news articles visible on landing page"


def test_landing_page_has_unique_title(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    title = page.title()
    assert title and "DevPlace" in title


def _help_section(page):
    return page.locator("section.landing-help")


def test_landing_build_with_us_section(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    section = _help_section(page)
    section.wait_for(state="visible", timeout=5000)
    assert section.locator("h2:has-text('Build With Us')").is_visible()
    assert section.locator(".landing-help-intro").is_visible()


def test_landing_help_docs_card(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    section = _help_section(page)
    section.wait_for(state="visible", timeout=5000)
    link = section.locator(".landing-help-card:has-text('Documentation') a.landing-help-link")
    assert link.get_attribute("href") == "/docs/index.html"


def test_landing_help_api_reference_links(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    section = _help_section(page)
    section.wait_for(state="visible", timeout=5000)
    card = section.locator(".landing-help-card:has-text('API Reference')")
    assert card.locator("a:has-text('Swagger UI')").get_attribute("href") == "/swagger"
    assert card.locator("a:has-text('OpenAPI JSON')").get_attribute("href") == "/openapi.json"


def test_landing_help_issue_tracker_link(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    section = _help_section(page)
    section.wait_for(state="visible", timeout=5000)
    link = section.locator(".landing-help-card:has-text('Contribute') a.landing-help-link")
    assert link.get_attribute("href") == "/issues"


def test_landing_help_devii_card_explained(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    section = _help_section(page)
    section.wait_for(state="visible", timeout=5000)
    card = section.locator(".landing-help-card:has-text('Meet Devii')")
    assert card.locator("h3:has-text('Meet Devii')").is_visible()
    assert "AI developer" in card.locator("p").first.text_content()
    assert card.locator("a.landing-help-link").get_attribute("href") == "/devii/"


def test_landing_help_launch_devii_button(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    section = _help_section(page)
    section.wait_for(state="visible", timeout=5000)
    button = section.locator("button.landing-help-cta[data-devii-open]")
    assert button.is_visible()
    assert "Launch Devii" in button.text_content()


def test_landing_launch_devii_opens_terminal(page, app_server):
    page.goto(f"{BASE_URL}/", wait_until="domcontentloaded")
    section = _help_section(page)
    section.wait_for(state="visible", timeout=5000)
    section.locator("button.landing-help-cta[data-devii-open]").click()
    page.locator("devii-terminal").wait_for(state="attached", timeout=5000)
