"""
Pages content generation engine for canada_dealer.
AI pre-check (skip if current content matches the prompt requirements) then generate (EN only).
Mirrors the shape of ai_descriptions.py.
"""
import json, re
from datetime import datetime

def _safe_json(raw):
    if isinstance(raw, dict):
        return raw
    if not isinstance(raw, str):
        return {}
    text = raw.strip()
    text = re.sub(r"^```(?:json|html)?\s*", "", text)
    text = re.sub(r"\s*```$", "", text)
    m = re.search(r"\{.*\}", text, re.DOTALL)
    if not m:
        return {}
    try:
        return json.loads(m.group(0))
    except Exception:
        return {}


def build_page_check_prompt(page, master_prompt, custom_prompt, current_content):
    title = page.get("title_en") or page.get("slug") or ""
    slug = page.get("slug") or ""
    custom = f"\nPAGE-SPECIFIC REQUIREMENTS:\n{custom_prompt}\n" if (custom_prompt or "").strip() else ""
    cur = (current_content or "")[:4000]
    return (
        f"You are a QA reviewer for a Canadian used-car dealership website page.\n"
        f"PAGE: {title} (slug: {slug})\n\n"
        f"MASTER REQUIREMENTS:\n{master_prompt}\n{custom}\n"
        f"CURRENT PAGE CONTENT (HTML):\n{cur}\n\n"
        f"Decide whether the CURRENT PAGE CONTENT already satisfies the MASTER REQUIREMENTS "
        f"(and PAGE-SPECIFIC REQUIREMENTS if any). Be strict: if any stated requirement is missing "
        f"or contradicted, it does NOT match.\n"
        f"Return JSON only: {{\"match\": true|false, \"reasons\": \"one line\"}}.\n"
        f"No markdown, no fences."
    )


def build_page_content_prompt(page, master_prompt, custom_prompt, current_content):
    title = page.get("title_en") or page.get("slug") or ""
    slug = page.get("slug") or ""
    custom = f"\nPAGE-SPECIFIC REQUIREMENTS (override/augment the master):\n{custom_prompt}\n" if (custom_prompt or "").strip() else ""
    cur = (current_content or "")[:2000]
    cur_section = f"\nEXISTING CONTENT (for reference; replace if it does not meet requirements):\n{cur}\n" if cur.strip() else ""
    return (
        f"You are an expert web copywriter for a Canadian used-car dealership in Toronto, Ontario.\n"
        f"PAGE: {title} (slug: {slug})\n\n"
        f"MASTER REQUIREMENTS:\n{master_prompt}\n{custom}{cur_section}\n"
        f"Write the English page content as compact, well-formed HTML (use <h2>, <p>, <ul><li>).\n"
        f"RULES:\n"
        f"- Canada only. NO USA/UK/Europe/VAT/Brexit/machinery references.\n"
        f"- Currency CAD. Use the {{COMPANY_NAME}} placeholder for the dealer name (do not invent a name).\n"
        f"- Use ONLY facts from the requirements; do not invent prices, addresses, phone numbers, or policies.\n"
        f"- No markdown, no code fences. Return JSON only: {{\"content_html\": \"...\"}}.\n"
        f"- Tight and professional; no novels."
    )


def generate_page_content(page_id, db, ai_call, master_prompt="", custom_prompt=""):
    """Pre-check then generate EN content for one page. Returns a dict with a 'status' key."""
    page = db.execute("SELECT * FROM site_pages WHERE id = ?", (page_id,)).fetchone()
    if not page:
        return {"status": "error", "error": f"Page {page_id} not found"}
    page = dict(page)  # convert sqlite3.Row to dict so .get() works in prompt builders

    master = (master_prompt or "").strip()
    custom = (custom_prompt or page["custom_prompt"] or "").strip()
    if not master and not custom:
        return {"status": "error", "error": "No master prompt set"}

    current = (page["content_html_en"] or "").strip()

    if current:
        try:
            raw = ai_call(build_page_check_prompt(page, master, custom, current))
            verdict = _safe_json(raw)
            if verdict.get("match") is True:
                return {"status": "skipped", "reasons": verdict.get("reasons", "")}
        except Exception as e:
            return {"status": "error", "error": f"Pre-check AI call failed: {e}"}

    try:
        raw = ai_call(build_page_content_prompt(page, master, custom, current))
        out = _safe_json(raw)
        html = (out.get("content_html") or "").strip()
    except Exception as e:
        return {"status": "error", "error": f"Generation AI call failed: {e}"}
    if not html:
        return {"status": "error", "error": "AI returned empty content_html"}

    html = re.sub(r"^```(?:html|json)?\s*", "", html)
    html = re.sub(r"\s*```$", "", html)
    now = datetime.utcnow().isoformat()
    db.execute(
        "UPDATE site_pages SET content_html_en = ?, english_updated_at = ?, updated_at = ? WHERE id = ?",
        (html, now, now, page_id),
    )
    db.commit()
    return {"status": "generated", "html": html}
