import argparse
from contextlib import closing
import re
import sqlite3
import sys
from pathlib import Path
from urllib.parse import urlsplit

PROJECT_ROOT = Path(__file__).resolve().parents[2]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from modules.core.app_factory import create_app
from modules.core import storage_paths
from InvestmentWebsite.services.offer_urls import build_offer_path


INDEXABLE_URLS = [
    "/",
    "/o-nas",
    "/franczyza",
    "/nieruchomosci/polska",
    "/nieruchomosci",
    "/nieruchomosci/strona/1",
    "/nieruchomosci/hiszpania",
    "/nieruchomosci/dubaj",
    "/nieruchomosci/hiszpania/costa-blanca",
    "/nieruchomosci/hiszpania/costa-del-sol",
    "/nieruchomosci/hiszpania/lanzarote",
    "/nieruchomosci/hiszpania/katalog/benidorm/apartamenty",
    "/nieruchomosci/hiszpania/katalog/lanzarote/houses",
    "/nieruchomosci/katalog/mieszkanie/sprzedaz",
]

NOINDEX_URLS = [
    {
        "url": "/nieruchomosci?q=test",
        "x_robots": "noindex, follow",
        "meta_robots": None,
    },
    {
        "url": "/nieruchomosci/hiszpania/katalog",
        "x_robots": "noindex, nofollow",
        "meta_robots": "noindex, nofollow",
    },
    {
        "url": "/nieruchomosci/hiszpania/katalog/lanzarote",
        "x_robots": "noindex, nofollow",
        "meta_robots": "noindex, nofollow",
    },
    {
        "url": "/nieruchomosci/hiszpania/katalog/benidorm/apartamenty?page=2",
        "x_robots": "noindex, follow",
        "meta_robots": None,
    },
    {
        "url": "/nieruchomosci/hiszpania/katalog/lanzarote/houses?lang=es",
        "x_robots": "noindex, follow",
        "meta_robots": None,
    },
    {
        "url": "/nieruchomosci/katalog/mieszkanie/sprzedaz?page=2",
        "x_robots": "noindex, follow",
        "meta_robots": None,
    },
    {
        "url": "/nieruchomosci/dubaj/catalog",
        "x_robots": "noindex, nofollow",
        "meta_robots": "noindex, nofollow",
    },
]

REQUIRED_HEAD_TOKENS = [
    "<title>",
    'meta name="description"',
    'rel="canonical"',
]

ALLOWED_DUPLICATE_TITLE_URL_SETS = [
    {"/nieruchomosci", "/nieruchomosci/strona/1"},
]

TITLE_RE = re.compile(r"<title>(.*?)</title>", re.IGNORECASE | re.DOTALL)
CANONICAL_RE = re.compile(
    r'<link\s+rel="canonical"\s+href="(.*?)"',
    re.IGNORECASE | re.DOTALL,
)
META_ROBOTS_RE = re.compile(
    r'<meta\s+name="robots"\s+content="(.*?)"',
    re.IGNORECASE | re.DOTALL,
)


def _find_active_offer_row():
    db_path = storage_paths.idb_db_path()
    if not db_path.is_file():
        return None
    try:
        with closing(sqlite3.connect(db_path.resolve().as_uri() + "?mode=ro", uri=True)) as conn:
            conn.execute("PRAGMA query_only=ON")
            cursor = conn.cursor()
            cursor.execute(
                """
                SELECT ID, Typ_nieruchomosci, Typ_oferty, Liczba_pokoi, Miejscowosc
                FROM EstateData
                WHERE Status_oferty='aktywna'
                ORDER BY ID DESC
                LIMIT 1
                """
            )
            return cursor.fetchone()
    except sqlite3.Error:
        print("[WARN] Cannot read the configured database; offer page check will be skipped.")
        return None


def _assert(condition, message, failures):
    if condition:
        print(f"[OK] {message}")
        return
    print(f"[FAIL] {message}")
    failures.append(message)


def _extract_first(regex, text):
    match = regex.search(text)
    if not match:
        return None
    return match.group(1).strip()


def _expected_canonical(base_url, raw_url):
    split = urlsplit(raw_url)
    path = split.path or "/"
    return f"{base_url.rstrip('/')}{path}"


def _is_allowed_duplicate(urls):
    normalized = set(urls)
    for allowed_set in ALLOWED_DUPLICATE_TITLE_URL_SETS:
        if normalized == allowed_set:
            return True
    return False


def run_smoke(skip_offer=False, base_url="http://localhost"):
    app = create_app()
    client = app.test_client()
    failures = []
    seen_titles = {}

    indexable_urls = list(INDEXABLE_URLS)
    if not skip_offer:
        offer_row = _find_active_offer_row()
        if offer_row:
            offer_id, property_type, offer_type, rooms, city = offer_row
            offer_url = build_offer_path(
                offer_id=offer_id,
                property_type=property_type,
                offer_type=offer_type,
                rooms=rooms,
                city=city,
            )
            indexable_urls.append(offer_url)
            print(f"[INFO] Active offer for test: {offer_id}")
        else:
            print("[WARN] Active offer not found, skipping offer page smoke test.")

    print("[INFO] Checking indexable pages")
    for url in indexable_urls:
        response = client.get(url, base_url=base_url)
        html = response.get_data(as_text=True)
        _assert(response.status_code == 200, f"{url} returns 200", failures)
        _assert(
            response.headers.get("X-Robots-Tag") is None,
            f"{url} has no X-Robots-Tag block",
            failures,
        )
        for token in REQUIRED_HEAD_TOKENS:
            _assert(token in html, f"{url} contains {token}", failures)

        title = _extract_first(TITLE_RE, html)
        _assert(bool(title), f"{url} has non-empty <title>", failures)
        if title:
            seen_titles.setdefault(title, []).append(url)

        canonical = _extract_first(CANONICAL_RE, html)
        expected_canonical = _expected_canonical(base_url, url)
        _assert(
            canonical == expected_canonical,
            f"{url} canonical matches expected ({expected_canonical})",
            failures,
        )

        meta_robots = _extract_first(META_ROBOTS_RE, html)
        _assert(meta_robots is None, f"{url} has no meta robots tag", failures)

    duplicate_titles = {t: urls for t, urls in seen_titles.items() if len(urls) > 1}
    unexpected_duplicates = {
        title: urls
        for title, urls in duplicate_titles.items()
        if not _is_allowed_duplicate(urls)
    }
    _assert(
        not unexpected_duplicates,
        "indexable pages have unique titles",
        failures,
    )
    if duplicate_titles:
        print(f"[INFO] duplicate titles (allowed+unexpected): {duplicate_titles}")

    print("[INFO] Checking noindex pages")
    for item in NOINDEX_URLS:
        url = item["url"]
        expected_x_robots = item["x_robots"]
        expected_meta_robots = item["meta_robots"]
        response = client.get(url, base_url=base_url)
        html = response.get_data(as_text=True)
        _assert(response.status_code == 200, f"{url} returns 200", failures)
        _assert(
            response.headers.get("X-Robots-Tag") == expected_x_robots,
            f"{url} has X-Robots-Tag='{expected_x_robots}'",
            failures,
        )
        meta_robots = _extract_first(META_ROBOTS_RE, html)
        _assert(
            meta_robots == expected_meta_robots,
            f"{url} meta robots is '{expected_meta_robots}'",
            failures,
        )

    print("[INFO] Checking sitemap")
    sitemap_response = client.get("/sitemap.xml", base_url=base_url)
    sitemap_xml = sitemap_response.get_data(as_text=True)
    _assert(sitemap_response.status_code == 200, "/sitemap.xml returns 200", failures)
    _assert("<urlset" in sitemap_xml, "sitemap has <urlset>", failures)
    _assert("<lastmod>" in sitemap_xml, "sitemap has <lastmod>", failures)
    _assert("<changefreq>" in sitemap_xml, "sitemap has <changefreq>", failures)
    _assert("<priority>" in sitemap_xml, "sitemap has <priority>", failures)
    _assert(
        "https://investment-nieruchomosci.com/nieruchomosci" in sitemap_xml,
        "sitemap contains core catalog URL",
        failures,
    )

    if failures:
        print(f"[RESULT] FAIL ({len(failures)} checks)")
        return 1

    print("[RESULT] PASS")
    return 0


def main():
    parser = argparse.ArgumentParser(description="SEO smoke checks for key routes.")
    parser.add_argument(
        "--skip-offer",
        action="store_true",
        help="Skip dynamic offer page check.",
    )
    parser.add_argument(
        "--base-url",
        default="http://localhost",
        help="Base URL used by Flask test client for canonical checks.",
    )
    args = parser.parse_args()
    exit_code = run_smoke(skip_offer=args.skip_offer, base_url=args.base_url)
    sys.exit(exit_code)


if __name__ == "__main__":
    main()
