"""
Genesis Domain Intelligence — PDF Report Generator
Generates client-facing audit reports from domain audit results.

Usage:
    python generate_report.py sunaivadigital.com
    python generate_report.py --json results/sunaivadigital.com.json

Output:
    PDF report saved to E:\genesis-system\tools\domain_audit\reports\{domain}_audit.pdf
"""

import sys
import os
import json
import argparse
from datetime import datetime

sys.path.append(os.path.dirname(os.path.abspath(__file__)))


def generate_audit_markdown(domain: str, audit_result: dict) -> str:
    """
    Generate Markdown content for the audit report PDF.
    Follows ReceptionistAI brand standards (professional, not folksy).
    """
    opportunities = audit_result.get("opportunities", [])
    tech = audit_result.get("technologies", {})
    whois = audit_result.get("whois", {})
    audit_score = audit_result.get("audit_score", 0)
    total_risk = audit_result.get("total_revenue_at_risk", 0)

    # Score color and label
    if audit_score >= 80:
        score_label = "Good Standing"
        score_color = "#22c55e"
    elif audit_score >= 60:
        score_label = "Needs Improvement"
        score_color = "#f59e0b"
    elif audit_score >= 40:
        score_label = "Significant Gaps"
        score_color = "#f97316"
    else:
        score_label = "Critical Issues Found"
        score_color = "#ef4444"

    # Extract tech stack
    tech_stack = tech.get("technologies", []) if isinstance(tech, dict) else []
    cms = next((t.get("name") for t in tech_stack if t.get("category") == "CMS"), "None detected")
    analytics = next((t.get("name") for t in tech_stack if t.get("category") == "Analytics"), "None detected")
    crm = next((t.get("name") for t in tech_stack if t.get("category") == "CRM"), "None detected")
    ecommerce = next((t.get("name") for t in tech_stack if t.get("category") == "Ecommerce"), "None detected")

    # Audit date
    audit_date = audit_result.get("audit_date", "")[:10] or datetime.now().strftime("%Y-%m-%d")

    markdown = f"""# Digital Health Audit

<div style="background: #0f172a; color: white; padding: 24px; border-radius: 8px; margin-bottom: 24px;">
<h2 style="color: white; margin: 0 0 8px 0; font-size: 28px;">{domain}</h2>
<p style="color: #94a3b8; margin: 0;">Audited by Genesis AI | {audit_date}</p>
</div>

## Overall Health Score

<div style="background: #f8fafc; border: 2px solid {score_color}; border-radius: 8px; padding: 20px; margin: 16px 0; text-align: center;">
<div style="font-size: 64px; font-weight: bold; color: {score_color};">{audit_score}</div>
<div style="font-size: 18px; color: #374151; margin-top: 4px;">{score_label}</div>
</div>

"""

    if total_risk > 0:
        markdown += f"""
<div style="background: #fef2f2; border-left: 4px solid #ef4444; padding: 16px; margin: 16px 0;">
<strong style="color: #b91c1c;">Estimated Revenue at Risk:</strong>
<span style="font-size: 20px; font-weight: bold; color: #b91c1c;"> ${total_risk:,}/month</span>
<br><small style="color: #6b7280;">Based on industry averages for businesses in your category</small>
</div>

"""

    markdown += """## Technology Stack

"""

    markdown += f"""| Category | Detected Tool |
|----------|--------------|
| Website CMS | {cms} |
| Web Analytics | {analytics} |
| CRM / Marketing | {crm} |
| E-commerce | {ecommerce} |
| AI Voice Receptionist | {"Active" if any(o["type"] != "no_ai_receptionist" for o in opportunities) else "**Not detected**"} |

"""

    if opportunities:
        markdown += f"""## Issues Found ({len(opportunities)} total)

"""
        # Critical first, then high, then medium
        for severity in ["critical", "high", "medium", "low"]:
            severity_opps = [o for o in opportunities if o.get("severity") == severity]
            if not severity_opps:
                continue

            severity_colors = {
                "critical": ("#fef2f2", "#ef4444", "CRITICAL"),
                "high": ("#fff7ed", "#f97316", "HIGH PRIORITY"),
                "medium": ("#fffbeb", "#f59e0b", "MEDIUM"),
                "low": ("#f0fdf4", "#22c55e", "LOW")
            }
            bg, border, label = severity_colors[severity]

            for opp in severity_opps:
                title = opp.get("type", "").replace("_", " ").title()
                pitch = opp.get("pitch", "")
                solution = opp.get("solution", "")
                impact = opp.get("revenue_impact", 0)

                markdown += f"""<div style="background: {bg}; border-left: 4px solid {border}; padding: 16px; margin: 12px 0; border-radius: 4px;">

**[{label}] {title}**

{pitch}

**Recommended solution:** {solution}

"""
                if impact > 0:
                    markdown += f"*Revenue impact: up to ${impact:,}/month recovered*\n\n"

                markdown += "</div>\n\n"

    else:
        markdown += """## No Critical Issues Found

Your digital presence is well-configured. Consider the recommendations below to further
optimise your lead capture and conversion rates.

"""

    markdown += """## What Happens Next?

Our team will walk you through each finding and show you exactly how to fix it.
Most issues can be resolved within 48 hours.

<div style="background: #0f172a; color: white; padding: 24px; border-radius: 8px; margin-top: 32px;">
<h3 style="color: white; margin: 0 0 12px 0;">Book Your Free Strategy Call</h3>
<p style="color: #94a3b8; margin: 0 0 8px 0;">We'll review this audit together and show you the fastest path to recovering lost revenue.</p>
<p style="color: white; font-weight: bold; margin: 0;">
    hello@sunaivadigital.com<br>
    sunaivadigital.com
</p>
<br>
<p style="color: #64748b; font-size: 12px; margin: 0;">
    ReceptionistAI — from $497/month. Setup fee waived for launch clients.<br>
    Powered by Genesis AI | sunaivadigital.com
</p>
</div>
"""

    return markdown


def save_report_as_pdf(domain: str, markdown_content: str) -> str:
    """
    Save report as PDF using Desktop Commander write_pdf tool.
    Returns path to generated PDF.
    Note: This function outputs the write_pdf call needed.
    The actual PDF creation requires the write_pdf MCP tool.
    """
    output_dir = "E:/genesis-system/tools/domain_audit/reports"
    os.makedirs(output_dir, exist_ok=True)

    # Save markdown version
    md_path = f"{output_dir}/{domain}_audit.md"
    with open(md_path, "w", encoding="utf-8") as f:
        f.write(markdown_content)

    pdf_path = f"{output_dir}/{domain}_audit.pdf"

    print(f"\nMarkdown report saved to: {md_path}")
    print(f"\nTo generate PDF, run in Claude Code:")
    print(f"  Use Desktop Commander write_pdf tool:")
    print(f"  path: {pdf_path}")
    print(f"  content: [content of {md_path}]")

    return pdf_path


def load_audit_result(domain: str) -> dict:
    """Load audit result from PostgreSQL or local JSON fallback."""
    # Try local JSON first
    json_path = f"E:/genesis-system/tools/domain_audit/results/{domain}.json"
    if os.path.exists(json_path):
        with open(json_path) as f:
            return json.load(f)

    # Try PostgreSQL
    try:
        sys.path.append("E:/genesis-system/data/genesis-memory")
        from elestio_config import PostgresConfig
        import psycopg2

        conn = psycopg2.connect(**PostgresConfig.get_connection_params())
        cur = conn.cursor()
        cur.execute(
            "SELECT raw_dataforseo_response FROM domain_audits WHERE domain = %s ORDER BY audit_date DESC LIMIT 1",
            (domain,)
        )
        row = cur.fetchone()
        cur.close()
        conn.close()

        if row:
            return row[0] if isinstance(row[0], dict) else json.loads(row[0])

    except Exception as e:
        print(f"PostgreSQL lookup failed: {e}")

    return {}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Genesis Domain Audit Report Generator")
    parser.add_argument("domain", nargs="?", default="sunaivadigital.com")
    parser.add_argument("--json", help="Path to audit result JSON file")
    args = parser.parse_args()

    if args.json:
        with open(args.json) as f:
            audit_result = json.load(f)
        domain = audit_result.get("domain", args.domain)
    else:
        domain = args.domain
        audit_result = load_audit_result(domain)

        if not audit_result:
            print(f"No audit result found for {domain}. Run audit_domain.py first.")
            sys.exit(1)

    markdown = generate_audit_markdown(domain, audit_result)
    pdf_path = save_report_as_pdf(domain, markdown)

    print(f"\nReport generated for: {domain}")
    print(f"Score: {audit_result.get('audit_score', 'N/A')}/100")
    print(f"Issues: {len(audit_result.get('opportunities', []))}")
    print(f"Revenue at risk: ${audit_result.get('total_revenue_at_risk', 0):,}/month")
