#!/usr/bin/env python3
"""Audit SEO on-page + liste candidats noindex legacy (P2.10)."""

from __future__ import annotations

import json
import re
import sys
import urllib.request
from html import unescape
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))

KEY_URLS = [
    "https://www.arnaud-merigeau.fr/",
    "https://www.arnaud-merigeau.fr/freelance-prestashop/",
    "https://www.arnaud-merigeau.fr/freelance-wordpress/",
    "https://www.arnaud-merigeau.fr/freelance-seo/",
    "https://www.arnaud-merigeau.fr/freelance-woocommerce/",
    "https://www.arnaud-merigeau.fr/freelance-prestashop-bordeaux/",
    "https://www.arnaud-merigeau.fr/freelance-wordpress-paris/",
    "https://www.arnaud-merigeau.fr/savoir-faire/",
]

LEGACY_PATTERNS = [
    "twitter",
    "concours",
    "facebook-like",
    "viadeo",
    "google-plus",
    "myspace",
]


def fetch(url: str) -> str:
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 SEO-Audit/1.0"})
    with urllib.request.urlopen(req, timeout=30) as resp:
        return resp.read().decode("utf-8", errors="replace")


def audit_page(url: str) -> dict:
    html = fetch(url)
    title = re.search(r"<title>([^<]+)</title>", html, re.I)
    meta = re.search(r'name="description"\s+content="([^"]*)"', html, re.I)
    canon = re.search(r'rel="canonical"\s+href="([^"]+)"', html, re.I)
    robots = re.search(r'name="robots"\s+content="([^"]+)"', html, re.I)
    h1 = len(re.findall(r"<h1[^>]*>", html, re.I))
    h2 = len(re.findall(r"<h2[^>]*>", html, re.I))
    ld = len(re.findall(r"application/ld\+json", html, re.I))
    text = re.sub(r"<script[^>]*>.*?</script>", " ", html, flags=re.I | re.S)
    text = re.sub(r"<style[^>]*>.*?</style>", " ", text, flags=re.I | re.S)
    words = len(re.sub(r"<[^>]+>", " ", text).split())

    issues = []
    if h1 != 1:
        issues.append(f"H1={h1} (attendu 1)")
    if not meta or len(meta.group(1)) < 120:
        issues.append(f"meta desc courte ({len(meta.group(1)) if meta else 0} car.)")
    if meta and len(meta.group(1)) > 165:
        issues.append("meta desc trop longue")
    if canon and canon.group(1).rstrip("/") != url.rstrip("/"):
        issues.append(f"canonical ≠ URL ({canon.group(1)})")
    if ld == 0:
        issues.append("pas de JSON-LD")
    if "noindex" in (robots.group(1) if robots else ""):
        issues.append("noindex")

    return {
        "url": url,
        "title": unescape(title.group(1).strip())[:90] if title else None,
        "meta_len": len(meta.group(1)) if meta else 0,
        "h1": h1,
        "h2": h2,
        "schema": ld,
        "words": words,
        "issues": issues,
    }


def legacy_candidates_from_sitemap() -> list[str]:
    xml = fetch("https://www.arnaud-merigeau.fr/post-sitemap.xml")
    urls = re.findall(r"<loc>(https://[^<]+)</loc>", xml)
    out = []
    for u in urls:
        slug = u.rstrip("/").split("/")[-1]
        if any(p in slug for p in LEGACY_PATTERNS):
            out.append(u)
    return out


def main() -> int:
    print("=== Audit SEO on-page ===")
    for url in KEY_URLS:
        try:
            r = audit_page(url)
            status = "OK" if not r["issues"] else "⚠ " + "; ".join(r["issues"])
            print(f"\n{r['url']}")
            print(f"  title: {r['title']}")
            print(f"  meta: {r['meta_len']} | H1: {r['h1']} | H2: {r['h2']} | schema: {r['schema']} | ~{r['words']} mots")
            print(f"  {status}")
        except Exception as exc:
            print(f"\n{url} ERROR: {exc}")

    print("\n=== Candidats legacy (motifs slug) ===")
    for u in legacy_candidates_from_sitemap()[:30]:
        print(f"  - {u}")
    print(f"Total motifs legacy dans sitemap: {len(legacy_candidates_from_sitemap())}")

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
