"""Content quality + keyword coverage + lead-generation audit."""
from __future__ import annotations
import re
from bs4 import BeautifulSoup


def analyze_content(url: str, html: str, target_keywords: list[str]) -> dict:
    soup = BeautifulSoup(html, "html.parser")
    text = soup.get_text(" ", strip=True).lower()
    title = (soup.title.string or "").lower() if soup.title else ""
    h_text = " ".join(h.get_text(" ", strip=True).lower()
                      for h in soup.find_all(["h1", "h2", "h3"]))

    keyword_report = []
    for kw in target_keywords:
        k = kw.lower()
        keyword_report.append({
            "keyword": kw,
            "in_title": k in title,
            "in_headings": k in h_text,
            "body_occurrences": text.count(k),
            "verdict": ("strong" if k in title and k in h_text
                        else "partial" if text.count(k) > 0
                        else "missing"),
        })

    words = re.findall(r"[a-zA-Z']+", text)
    sentences = [s for s in re.split(r"[.!?]+", text) if s.strip()]
    avg_len = (len(words) / len(sentences)) if sentences else 0

    return {
        "url": url,
        "word_count": len(words),
        "avg_sentence_length": round(avg_len, 1),
        "readability_note": ("Good — conversational sentence length"
                             if avg_len <= 20 else
                             "Long sentences — shorten for humans AND for LLM chunking"),
        "keywords": keyword_report,
        "internal_links": len([a for a in soup.find_all("a", href=True)
                               if not a["href"].startswith(("http", "//"))
                               or url.split("/")[2] in a["href"]]),
    }


LEAD_SIGNALS = {
    "contact_form": (r"<form", "A form exists (contact/lead capture)"),
    "tel_link": (r'href="tel:', "Click-to-call phone link"),
    "mailto": (r'href="mailto:', "Email link"),
    "whatsapp": (r"wa\.me|api\.whatsapp", "WhatsApp contact link"),
    "cta_button": (r"(book now|get (a )?quote|contact us|free consult|sign up|"
                   r"get started|request demo|call now|enquire|order now)",
                   "Clear call-to-action text"),
    "map_embed": (r"google\.com/maps|maps\.googleapis", "Embedded map (local trust)"),
    "reviews": (r"(testimonial|review|rating|stars)", "Reviews/testimonials present"),
    "chat_widget": (r"(tawk\.to|crisp\.chat|intercom|drift\.com|tidio|livechat)",
                    "Live chat widget"),
}


def audit_lead_gen(url: str, html: str) -> dict:
    low = html.lower()
    found, missing = [], []
    for key, (pattern, desc) in LEAD_SIGNALS.items():
        (found if re.search(pattern, low) else missing).append(desc)
    score = round(100 * len(found) / len(LEAD_SIGNALS), 1)

    recs = []
    if score < 60:
        recs.append("Add at least one above-the-fold CTA (button + short benefit statement). [needs manual content work — layout decision]")
    if "Click-to-call phone link" in missing:
        recs.append("Add href='tel:' phone links — mobile users convert via one-tap call. [auto-fixable once you add your real phone number in Settings \u2192 Business Facts]")
    if "Reviews/testimonials present" in missing:
        recs.append("Surface reviews with Review/AggregateRating schema — boosts both Google stars and AI-answer trust. [auto-fixable once you add real testimonials in Settings \u2192 Business Facts]")
    if "A form exists (contact/lead capture)" in missing:
        recs.append("Add a short lead form (name, phone, need) — 3 fields max converts best. [needs manual content work — needs a form backend]")
    return {"url": url, "score": score, "present": found,
            "missing": missing, "recommendations": recs}
