"""Édition 2, phase A : lit la page d'accueil de chaque fiche (H4, H5, H6 en mesure de repli, H8). 0 $, aucun appel payant.

Règles : ops/etude/v2/definitions_sites.md (écrites avant toute analyse). Une requête GET par adresse, robots.txt respecté,
robot déclaré. Rien n'est gardé du HTML sauf les valeurs dérivées et une empreinte. Le téléphone de la fiche est lu dans les
listes brutes pour la comparaison et n'est écrit nulle part.

    PYTHONPATH=. .venv/bin/python -u ops/etude/v2/sites_phase_a.py        # reprend là où il s'est arrêté
Écrit ops/etude/v2/donnees/sites.csv.gz (une ligne par fiche avec site).
"""
from __future__ import annotations

import csv
import gzip
import hashlib
import json
import re
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from html.parser import HTMLParser
from pathlib import Path
from urllib import robotparser
from urllib.parse import urljoin, urlparse

import httpx
import pandas as pd

sys.path.insert(0, str(Path(__file__).parents[1]))
from commun import seq  # noqa: E402

from core.text import slugify  # noqa: E402

HERE = Path(__file__).parent
OUT = HERE / "donnees" / "sites.jsonl"
UA = "FoundByNameResearch/1.0 (+https://foundbyname.com/study/ai-local-search)"
TIMEOUT, MAX_BYTES, WORKERS, MIN_TEXT = 20.0, 3_000_000, 8, 300
SOCIAL = ("facebook.com", "instagram.com", "linkedin.com", "x.com", "twitter.com", "yelp.com", "tiktok.com", "youtube.com",
          "linktr.ee", "google.com", "goo.gl", "business.site")
ORG = set(json.loads((HERE / "ref" / "organization_types.json").read_text()))
TRADE = {
    "dentist": (["dentist", "dental", "dentistry"],
                ["implant", "crown", "cleaning", "whitening", "invisalign", "root canal", "veneer", "filling", "extraction", "orthodont"]),
    "personal-injury-lawyer": (["injury", "accident lawyer", "accident attorney", "law firm", "attorney", "lawyer"],
                               ["car accident", "truck accident", "slip and fall", "wrongful death", "motorcycle", "dog bite",
                                "workers comp", "medical malpractice"]),
    "med-spa": (["med spa", "medspa", "medical spa", "aesthetic", "medical aesthetics"],
                ["botox", "filler", "laser", "hydrafacial", "microneedling", "coolsculpting", "chemical peel", "dysport",
                 "iv therapy", "weight loss"]),
    "plumber": (["plumber", "plumbing"],
                ["water heater", "drain", "leak", "sewer", "pipe", "toilet", "garbage disposal", "faucet", "gas line"]),
    "hvac-contractor": (["hvac", "heating", "air conditioning", "cooling", "heating and air"],
                        ["furnace", "air conditioner", "heat pump", "duct", "thermostat", "ac repair", "ac installation", "boiler",
                         "mini split"]),
    "roofer": (["roofing", "roofer", "roof"],
               ["shingle", "roof repair", "roof replacement", "storm damage", "gutter", "metal roof", "roof inspection",
                "flat roof", "hail"]),
    "veterinarian": (["veterinar", "animal hospital", "vet clinic", "pet hospital"],
                     ["vaccin", "spay", "neuter", "dental", "surgery", "wellness", "exam", "microchip", "emergency"]),
    "chiropractor": (["chiropract"],
                     ["adjustment", "back pain", "neck pain", "sciatica", "massage", "spinal decompression", "headache", "posture"]),
    "real-estate-agent": (["real estate", "realtor", "realty"],
                          ["buy", "sell", "listing", "home valuation", "first-time", "homes for sale", "relocation"]),
    "auto-repair-shop": (["auto repair", "auto service", "mechanic", "car repair", "automotive"],
                         ["brake", "oil change", "transmission", "engine", "alignment", "tire", "diagnostic", "suspension", "ac repair"]),
}


def has_word(text: str, w: str) -> bool:
    return re.search(r"\b" + re.escape(w), text) is not None


class Page(HTMLParser):
    SKIP = {"script", "style", "noscript", "template", "svg"}

    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.text, self.links, self.ld, self._skip, self._ld = [], [], [], 0, None

    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        if tag == "script" and (a.get("type") or "").lower().strip() == "application/ld+json":
            self._ld = []
        if tag in self.SKIP:
            self._skip += 1
        if tag == "a" and a.get("href"):
            self.links.append(a["href"])

    def handle_endtag(self, tag):
        if tag == "script" and self._ld is not None:
            self.ld.append("".join(self._ld))
            self._ld = None
        if tag in self.SKIP and self._skip:
            self._skip -= 1

    def handle_data(self, data):
        if self._ld is not None:
            self._ld.append(data)
        elif not self._skip:
            self.text.append(data)


def ld_types(blocks: list[str]) -> list[str]:
    out = []

    def walk(o):
        if isinstance(o, list):
            for x in o:
                walk(x)
        elif isinstance(o, dict):
            t = o.get("@type")
            for x in (t if isinstance(t, list) else [t]):
                if isinstance(x, str):
                    out.append(x.split("/")[-1].split(":")[-1])
            if "@graph" in o:
                walk(o["@graph"])
    for b in blocks:
        try:
            walk(json.loads(b.strip()))
        except Exception:  # noqa: BLE001 — un JSON-LD cassé compte comme absent
            continue
    return out


_robots: dict[str, robotparser.RobotFileParser | None] = {}
_rlock = threading.Lock()


def allowed(client: httpx.Client, url: str) -> bool:
    p = urlparse(url)
    root = f"{p.scheme}://{p.netloc}"
    with _rlock:
        if root in _robots:
            rp = _robots[root]
            return True if rp is None else rp.can_fetch(UA, url)
    rp = None
    try:
        r = client.get(root + "/robots.txt", timeout=10)
        if r.status_code == 200 and len(r.content) < 500_000:
            rp = robotparser.RobotFileParser()
            rp.parse(r.text.splitlines())
    except Exception:  # noqa: BLE001 — pas de robots.txt lisible : la page reste permise
        rp = None
    with _rlock:
        _robots[root] = rp
    return True if rp is None else rp.can_fetch(UA, url)


def one(client: httpx.Client, row: dict) -> dict:
    url = row["website"].strip()
    if not url.startswith("http"):
        url = "http://" + url
    host = urlparse(url).netloc.lower().removeprefix("www.")
    base = {"market": row["market"], "place_id": row["place_id"], "url": url}
    if any(host == s or host.endswith("." + s) for s in SOCIAL):
        return {**base, "status": "social", "reachable": False}
    if not allowed(client, url):
        return {**base, "status": "robots", "reachable": False}
    try:
        with client.stream("GET", url, timeout=TIMEOUT) as r:
            ctype = r.headers.get("content-type", "")
            body = b""
            for chunk in r.iter_bytes():
                body += chunk
                if len(body) > MAX_BYTES:
                    break
            final, code = str(r.url), r.status_code
            enc = r.encoding or "utf-8"
    except Exception as exc:  # noqa: BLE001
        return {**base, "status": f"error:{type(exc).__name__}", "reachable": False}
    if code >= 400 or "html" not in ctype.lower():
        return {**base, "status": f"http:{code}", "final_url": final, "reachable": False}
    html = body.decode(enc, errors="replace")
    pg = Page()
    try:
        pg.feed(html)
    except Exception:  # noqa: BLE001
        pass
    text = re.sub(r"\s+", " ", " ".join(pg.text)).strip()
    low = text.lower()
    types = ld_types(pg.ld)
    trade_words, services = TRADE[row["category"]]
    city = (row["market_city"] or "").lower()
    city2 = (row["city"] or "").lower() if isinstance(row["city"], str) else ""
    links = [urljoin(final, h) for h in pg.links]
    tel = "".join(re.sub(r"\D", "", h) for h in pg.links if h.lower().startswith("tel:"))
    digits = re.sub(r"\D", "", text) + tel
    phone = re.sub(r"\D", "", row.get("phone") or "")[-10:]
    name_words = seq(re.split(r"\s[-–—]\s|[,(:/|]", row["name"] or "")[0])
    street = row.get("street") or ""
    m = re.match(r"\s*(\d+[a-z]?)\s+(.+)", street.lower())
    empty = len(text) < MIN_TEXT
    out = {**base, "status": f"http:{code}", "final_url": final, "reachable": True, "text_len": len(text), "empty": empty,
           "html_sha256": hashlib.sha256(body).hexdigest(), "ld_types": "|".join(sorted(set(types))),
           "schema_org": int(any(t in ORG for t in types)),
           "links_yelp": int(any("yelp.com/biz/" in h.lower() for h in links)),
           "links_healthgrades": int(any("healthgrades.com" in h.lower() for h in links))}
    if not empty:
        trade_ok = any(has_word(low, w) for w in trade_words)
        city_ok = bool(city) and city in low or bool(city2) and city2 in low
        serv_ok = any(has_word(low, w) for w in services)
        name_ok = bool(name_words) and all(re.search(r"\b" + re.escape(w) + r"\b", low) for w in name_words)
        addr_ok = None
        if m:
            num, rest = m.group(1), m.group(2).split()
            first = next((w for w in rest if w not in {"n", "s", "e", "w", "ne", "nw", "se", "sw", "north", "south", "east", "west"}), "")
            addr_ok = bool(re.search(r"\b" + re.escape(num) + r"\b", low)) and bool(first) and has_word(low, first)
        phone_ok = len(phone) == 10 and phone in digits
        out.update({"trade_ok": int(trade_ok), "city_ok": int(city_ok), "service_ok": int(serv_ok),
                    "content_ok": int(trade_ok and city_ok and serv_ok), "name_ok": int(name_ok),
                    "address_ok": None if addr_ok is None else int(addr_ok), "phone_ok": int(phone_ok),
                    "nap_consistent": int(name_ok and phone_ok and (addr_ok is None or addr_ok))})
    return out


def rows() -> list[dict]:
    mk = {(slugify(m["city"]), m["trade"]): m for m in csv.DictReader((HERE / "marches_phase_a.csv").open())}
    out = []
    for (slug, trade), m in mk.items():
        d = json.loads(gzip.decompress((HERE / "listes" / f"{slug}__{trade}.json.gz").read_bytes()))
        for it in d["items"]:
            if it.get("permanentlyClosed") or not it.get("website"):
                continue
            out.append({"market": f"{slug}|{trade}", "category": trade, "market_city": m["city"], "place_id": it.get("placeId"),
                        "name": it.get("title"), "website": it.get("website"), "city": it.get("city"), "street": it.get("street"),
                        "phone": it.get("phone")})
    return out


if __name__ == "__main__":
    todo = rows()
    done = set()
    if OUT.exists():
        for line in OUT.open():
            r = json.loads(line)
            done.add((r["market"], r["place_id"]))
    todo = [r for r in todo if (r["market"], r["place_id"]) not in done]
    print(f"{len(todo)} sites à lire ({len(done)} déjà lus)", flush=True)
    lock = threading.Lock()
    n = 0
    t0 = time.time()
    with httpx.Client(headers={"User-Agent": UA, "Accept": "text/html,application/xhtml+xml"}, follow_redirects=True,
                      timeout=TIMEOUT, limits=httpx.Limits(max_connections=WORKERS * 2)) as client, OUT.open("a") as fh:
        with ThreadPoolExecutor(WORKERS) as pool:
            futs = [pool.submit(one, client, r) for r in todo]
            for f in as_completed(futs):
                try:
                    r = f.result()
                except Exception as exc:  # noqa: BLE001
                    continue
                with lock:
                    fh.write(json.dumps(r, ensure_ascii=False) + "\n")
                    n += 1
                    if n % 500 == 0:
                        fh.flush()
                        print(f"{n}/{len(todo)} · {time.time() - t0:.0f} s", flush=True)
    df = pd.read_json(OUT, lines=True)
    with gzip.open(HERE / "donnees" / "sites.csv.gz", "wt", encoding="utf-8", newline="") as fh:
        df.drop(columns=["url"]).to_csv(fh, index=False)
    print("FINI", len(df), df.status.str.split(":").str[0].value_counts().to_dict(),
          "joignables", int(df.reachable.sum()), "schema", int(df.get("schema_org", pd.Series()).fillna(0).sum()), flush=True)
