"""
Calls the Anthropic API to turn everything the dashboard already knows about
a site — non-indexed pages and why, current technical/mobile health, and
competitor benchmarks — into specific, actionable recommendations.

Requires ANTHROPIC_API_KEY in .env. Get one at https://console.anthropic.com
"""
import requests

ANTHROPIC_API_URL = 'https://api.anthropic.com/v1/messages'
ANTHROPIC_VERSION = '2023-06-01'


def _build_context(site, not_indexed_pages, health, competitor_rows, keywords):
    lines = [f"SITE: {site.name} — {site.url}", ""]

    # Indexing issues
    lines.append("## Pages not properly indexed (from Google Search Console URL Inspection)")
    if not_indexed_pages:
        for p in not_indexed_pages:
            lines.append(f"- {p.url}\n  verdict: {p.verdict}, coverage: {p.coverage_state}, reason: {p.reason}")
    else:
        lines.append("- None currently flagged — all inspected pages are indexed normally.")
    lines.append("")

    # Technical / mobile health
    lines.append("## Current technical & mobile-responsiveness signals for our site")
    if health:
        lines.append(f"- HTTP status: {health.http_status}, response time: {health.response_time_ms}ms")
        lines.append(f"- Title length: {health.title_length} chars, meta description length: {health.meta_desc_length} chars")
        lines.append(f"- H1 count: {health.h1_count}, word count: {health.word_count}")
        lines.append(f"- Has viewport meta tag: {health.has_viewport_meta}")
        lines.append(f"- CSS @media breakpoints detected: {health.media_query_count}")
        lines.append(f"- Broken internal links: {health.broken_links_count}")
        lines.append(f"- robots.txt reachable: {health.robots_txt_ok}, sitemap.xml found: {health.sitemap_found}")
    else:
        lines.append("- No health check data yet.")
    lines.append("")

    # Competitors
    lines.append("## Competitor benchmark (same signals, for comparison)")
    if competitor_rows:
        for comp, snap in competitor_rows:
            if snap:
                lines.append(
                    f"- {comp.url} — title: \"{snap.title}\" ({len(snap.title or '')} chars), "
                    f"word count: {snap.word_count}, H1s: {snap.h1_count}, "
                    f"viewport tag: {snap.has_viewport_meta}, media queries: {snap.media_query_count}, "
                    f"PSI performance: {snap.psi_performance}, PSI SEO: {snap.psi_seo}"
                )
            else:
                lines.append(f"- {comp.url} — no snapshot data yet")
    else:
        lines.append("- No competitors added yet.")
    lines.append("")

    # Keywords
    lines.append("## Top search queries currently driving clicks (Search Console)")
    if keywords:
        for k in keywords[:15]:
            lines.append(f"- \"{k.search_query}\" — clicks: {k.clicks}, impressions: {k.impressions}, avg position: {k.position}")
    else:
        lines.append("- No keyword data yet.")

    return "\n".join(lines)


SYSTEM_PROMPT = """You are a senior SEO and web performance consultant reviewing a client's \
WordPress site for an agency. You are given structured data pulled from Google Search Console, \
PageSpeed Insights, and a technical crawler, plus the same signals for one or more competitor URLs. \
Write a specific, actionable recommendation report in Markdown with exactly these three sections, \
in this order, using ## headings:

## Indexing fixes
For each non-indexed page, give the most likely root cause in plain language and a concrete fix \
(e.g. "thin content — expand to 400+ words covering X, Y, Z", "blocked by robots.txt — remove the \
disallow rule for this path", "not yet crawled — add to sitemap and request indexing in Search \
Console"). If nothing is flagged, briefly say indexing looks healthy and note one thing to watch.

## Competitor-based improvements
Compare our site's signals against each competitor. Call out concrete gaps (content depth, title/meta \
quality, technical setup, performance scores) and give a specific "do this instead" recommendation for \
each gap you find — not generic advice. If no competitors were provided, say so and skip this section's detail.

## Design & mobile-responsiveness
Based only on the technical signals given (viewport tag presence, CSS @media breakpoint count, PSI \
mobile scores), assess whether the site is likely mobile-responsive and give specific fixes if not \
(e.g. "add a viewport meta tag", "the theme's CSS has no breakpoints below 768px — audit templates for \
fixed pixel widths"). Be honest that this is a technical-signal read, not a visual review.

Keep it concrete and prioritized. No preamble, no "here is your report" — start directly with the \
first heading."""


def generate_recommendations(api_key, model, site, not_indexed_pages, health, competitor_rows, keywords):
    """
    Returns (markdown_text, error). On success error is None; on failure markdown_text is None.
    """
    context = _build_context(site, not_indexed_pages, health, competitor_rows, keywords)

    payload = {
        'model': model,
        'max_tokens': 2000,
        'system': SYSTEM_PROMPT,
        'messages': [{'role': 'user', 'content': context}],
    }
    headers = {
        'x-api-key': api_key,
        'anthropic-version': ANTHROPIC_VERSION,
        'content-type': 'application/json',
    }

    try:
        resp = requests.post(ANTHROPIC_API_URL, json=payload, headers=headers, timeout=90)
        resp.raise_for_status()
        data = resp.json()
    except requests.RequestException as e:
        return None, str(e)

    text_blocks = [b['text'] for b in data.get('content', []) if b.get('type') == 'text']
    if not text_blocks:
        return None, f"No text content in API response: {data}"

    return "\n".join(text_blocks), None
