"""
rule_engine.py
Rule-based scoring system (growth marketing & SEO best practices).
Each rule produces a per-category score penalty plus a recommendation,
with estimated impact, effort, and time to implement.
"""

CATEGORIES = [
    "seo_foundation",
    "trust_credibility",
    "user_experience",
    "conversion_optimization",
    "content_quality",
    "technical_performance",
    "accessibility",
]

CATEGORY_LABELS = {
    "seo_foundation": "SEO Foundation",
    "trust_credibility": "Trust & Credibility",
    "user_experience": "User Experience",
    "conversion_optimization": "Conversion Optimization",
    "content_quality": "Content Quality",
    "technical_performance": "Technical Performance",
    "accessibility": "Accessibility",
}

# Weight of each category toward the final Growth Score (total = 1.0)
CATEGORY_WEIGHTS = {
    "seo_foundation": 0.18,
    "trust_credibility": 0.16,
    "user_experience": 0.14,
    "conversion_optimization": 0.20,
    "content_quality": 0.14,
    "technical_performance": 0.10,
    "accessibility": 0.08,
}


def _rec(id_, category, title, why, impact, effort, minutes):
    """Build one standardized recommendation object."""
    return {
        "id": id_,
        "category": category,
        "title": title,
        "why_it_matters": why,
        "impact": impact,       # "high" | "medium" | "low"
        "effort": effort,       # "high" | "medium" | "low"
        "estimated_minutes": minutes,
    }


def run_rules(data: dict):
    """
    Evaluate scraped data against every rule.
    Returns: (category_scores: dict[str,int 0-100], recommendations: list[dict], issues_count: int)
    """
    scores = {c: 100 for c in CATEGORIES}
    recs = []

    def penalize(category, points):
        scores[category] = max(0, scores[category] - points)

    # ---------------- SEO Foundation ----------------
    if not data["title"]:
        penalize("seo_foundation", 25)
        recs.append(_rec("seo-title-missing", "seo_foundation",
                          "Add a <title> tag to the page",
                          "The title tag is the most basic SEO signal and shows up in search results and the browser tab.",
                          "high", "low", 10))
    elif data["title_length"] < 15 or data["title_length"] > 65:
        penalize("seo_foundation", 8)
        recs.append(_rec("seo-title-length", "seo_foundation",
                          "Optimize the title length (aim for 15-65 characters)",
                          "Titles that are too short or too long can get cut off in Google search results.",
                          "medium", "low", 10))

    if not data["meta_description"]:
        penalize("seo_foundation", 15)
        recs.append(_rec("seo-meta-missing", "seo_foundation",
                          "Add a meta description",
                          "A meta description improves click-through rate from search results.",
                          "medium", "low", 15))

    if data["h1_count"] == 0:
        penalize("seo_foundation", 20)
        recs.append(_rec("seo-h1-missing", "seo_foundation",
                          "Add one clear H1 heading",
                          "An H1 helps both search engines and users understand the page's main topic.",
                          "high", "low", 10))
    elif data["h1_count"] > 1:
        penalize("seo_foundation", 8)
        recs.append(_rec("seo-h1-multiple", "seo_foundation",
                          "Use only one H1 per page",
                          "Multiple H1 tags confuse the page's content structure for SEO.",
                          "low", "low", 10))

    if not data["is_https"]:
        penalize("seo_foundation", 15)
        recs.append(_rec("seo-https", "seo_foundation",
                          "Enable HTTPS/SSL",
                          "Google ranks non-HTTPS sites lower, and browsers flag them as 'not secure'.",
                          "high", "medium", 60))

    # ---------------- Trust & Credibility ----------------
    if not data["has_testimonial"]:
        penalize("trust_credibility", 25)
        recs.append(_rec("trust-testimonial", "trust_credibility",
                          "Add testimonials or customer reviews",
                          "Social proof significantly increases trust with prospective customers.",
                          "high", "medium", 60))

    if not data["emails"] and not data["phones"] and not data["whatsapp_links"]:
        penalize("trust_credibility", 25)
        recs.append(_rec("trust-contact", "trust_credibility",
                          "Add clear contact info (email/phone/WhatsApp)",
                          "Missing contact details make visitors doubt the business's credibility.",
                          "high", "low", 15))

    if not data["has_address_hint"]:
        penalize("trust_credibility", 15)
        recs.append(_rec("trust-address", "trust_credibility",
                          "Add a physical business address",
                          "A clear address builds trust, especially for local or small businesses.",
                          "medium", "low", 15))

    if not data["social_links"]:
        penalize("trust_credibility", 15)
        recs.append(_rec("trust-social", "trust_credibility",
                          "Link to active social media accounts",
                          "Social links signal that the business is active and trustworthy.",
                          "medium", "low", 20))

    # ---------------- User Experience ----------------
    if data["load_time_seconds"] > 3:
        penalize("user_experience", 25)
        recs.append(_rec("ux-load-time", "user_experience",
                          "Speed up page load time (currently over 3 seconds)",
                          "Every extra second of load time can significantly reduce conversions.",
                          "high", "high", 240))

    if not data["has_viewport"]:
        penalize("user_experience", 25)
        recs.append(_rec("ux-mobile", "user_experience",
                          "Add a meta viewport tag for mobile responsiveness",
                          "Most traffic today comes from mobile devices.",
                          "high", "low", 15))

    if data["nav_links_count"] > 10:
        penalize("user_experience", 10)
        recs.append(_rec("ux-nav-complex", "user_experience",
                          "Simplify the navigation (too many menu items)",
                          "Complex navigation makes it harder for visitors to find what they need.",
                          "low", "medium", 60))

    if data["nav_links_count"] == 0:
        penalize("user_experience", 10)

    # ---------------- Conversion Optimization ----------------
    if data["cta_count"] == 0:
        penalize("conversion_optimization", 35)
        recs.append(_rec("cvo-cta-missing", "conversion_optimization",
                          "Add a clear Call-to-Action (CTA) button",
                          "A CTA guides visitors toward the action that drives conversions or sales.",
                          "high", "low", 20))
    elif data["cta_count"] == 1:
        penalize("conversion_optimization", 10)

    if data["form_count"] == 0:
        penalize("conversion_optimization", 20)
        recs.append(_rec("cvo-form-missing", "conversion_optimization",
                          "Add a contact or booking form",
                          "A form makes it easier for visitors to take action without leaving the page.",
                          "medium", "medium", 45))

    if not data["has_faq"]:
        penalize("conversion_optimization", 15)
        recs.append(_rec("cvo-faq-missing", "conversion_optimization",
                          "Add an FAQ section",
                          "An FAQ answers prospective customers' doubts before they ask, speeding up buying decisions.",
                          "medium", "medium", 60))

    # ---------------- Content Quality ----------------
    if data["word_count"] < 150:
        penalize("content_quality", 30)
        recs.append(_rec("content-thin", "content_quality",
                          "Add more content to the page (currently too thin)",
                          "Thin content is less informative for visitors and less favored by search engines.",
                          "medium", "medium", 90))

    if data["h2_count"] == 0:
        penalize("content_quality", 15)
        recs.append(_rec("content-subheading", "content_quality",
                          "Add subheadings (H2) to structure the content",
                          "Subheadings make it easier for readers to scan for key information.",
                          "low", "low", 20))

    # ---------------- Technical Performance ----------------
    if data["load_time_seconds"] > 3:
        penalize("technical_performance", 30)
    if data["images_total"] > 0 and data["images_missing_alt"] / max(data["images_total"], 1) > 0.5:
        penalize("technical_performance", 15)

    # ---------------- Accessibility ----------------
    if data["images_total"] > 0:
        missing_ratio = data["images_missing_alt"] / data["images_total"]
        if missing_ratio > 0:
            penalty = min(35, int(missing_ratio * 40))
            penalize("accessibility", penalty)
            recs.append(_rec("a11y-alt-text", "accessibility",
                              f"Add alt text to {data['images_missing_alt']} images",
                              "Alt text helps screen reader users and also improves image SEO.",
                              "medium", "low", 30))

    if data["h1_count"] == 0:
        penalize("accessibility", 10)

    issues_count = len(recs)
    return scores, recs, issues_count
