import re
from pathlib import Path


CDN_PATTERNS = re.compile(
    r"(cdn\.jsdelivr\.net|unpkg\.com|cdnjs\.com)",
    re.IGNORECASE,
)

# Matches href="https://..." or src="https://..."
EXTERNAL_URL_PATTERN = re.compile(
    r'(?:href|src)=["\']https?://',
    re.IGNORECASE,
)


def test_no_cdn_urls_in_templates():
    """All .html templates use /static/ paths only — no CDN URLs in href/src attributes."""
    templates_dir = Path(__file__).parent.parent / "imptune" / "templates"
    html_files = list(templates_dir.glob("**/*.html"))
    assert html_files, "No HTML templates found — check templates directory path"

    violations = []
    for html_file in html_files:
        content = html_file.read_text(encoding="utf-8")
        if CDN_PATTERNS.search(content):
            violations.append(f"{html_file.name}: contains CDN domain reference")
        if EXTERNAL_URL_PATTERN.search(content):
            violations.append(f"{html_file.name}: contains external https:// in href/src")

    assert not violations, "CDN/external URL violations found:\n" + "\n".join(violations)


def test_dashboard_returns_200(client):
    """GET / returns 200 (dashboard page)."""
    response = client.get("/")
    assert response.status_code == 200


def test_packages_returns_200(client):
    """GET /packages returns 200 (packages listing page)."""
    response = client.get("/packages")
    assert response.status_code == 200


def test_dashboard_shows_recent_printers(client):
    """Dashboard renders names of recently-created printers from DB."""
    from imptune.db.models import Printer

    Printer.create(
        name="TestPrinter-Alpha",
        ip_address="10.0.0.1",
        port_name="IP_10.0.0.1",
    )
    Printer.create(
        name="TestPrinter-Beta",
        ip_address="10.0.0.2",
        port_name="IP_10.0.0.2",
    )

    response = client.get("/")
    assert response.status_code == 200
    assert "TestPrinter-Alpha" in response.text
    assert "TestPrinter-Beta" in response.text
    assert "No printers configured yet" not in response.text


def test_dashboard_shows_recent_packages(client):
    """Dashboard recent-packages section shows only printers with a driver assigned."""
    from imptune.db.models import Driver, Printer

    driver = Driver.create(
        sha256="abc123",
        original_filename="test.zip",
        size_bytes=1000,
        driver_desc='["TestDriver"]',
    )
    Printer.create(
        name="PkgPrinter-Assigned",
        ip_address="10.0.0.2",
        port_name="IP_10.0.0.2",
        driver=driver,
    )
    Printer.create(
        name="PkgPrinter-NoDriver",
        ip_address="10.0.0.3",
        port_name="IP_10.0.0.3",
    )

    response = client.get("/")
    assert response.status_code == 200
    assert "PkgPrinter-Assigned" in response.text
    assert "No packages exported yet" not in response.text
