"""
report_service.py
-------------------
Builds the auto-generated research report (Deliverable #10 in the spec):
participant ID, screening scores, AI risk assessment, conversation summary,
a simple inline SVG bar chart, suggested next steps, and the mandatory
non-diagnostic disclaimer.

Output is a self-contained HTML string (no external assets) so it can be
stored in the `reports` table and rendered directly, or converted to PDF
later with a tool like WeasyPrint if needed.
"""

from datetime import datetime
from typing import Dict, List


DISCLAIMER = (
    "This report was generated by MindScreen AI, a research and educational "
    "screening tool. It is <strong>not a medical diagnosis</strong> and does "
    "not replace evaluation by a licensed mental health professional. If you "
    "are concerned about your wellbeing, please consult a doctor or licensed "
    "clinician, and if you are in crisis, contact your local emergency "
    "number or a crisis line (e.g. 988 in the US)."
)

NEXT_STEPS_BY_LEVEL = {
    "Low": "Your responses suggest relatively low levels of distress right "
           "now. Continuing healthy routines (sleep, movement, social "
           "connection) and rechecking in periodically is reasonable.",
    "Moderate": "Your responses suggest a moderate level of distress. "
                "Consider talking to a counselor, doctor, or trusted campus/"
                "workplace mental health resource — earlier support tends to "
                "help more than waiting.",
    "High": "Your responses suggest a high level of distress. We strongly "
            "encourage reaching out to a licensed mental health professional "
            "soon, and to a trusted person in your life. If you ever feel in "
            "immediate danger, contact emergency services or a crisis line "
            "right away.",
}


def _overall_level(result_dict: Dict) -> str:
    levels = [result_dict["depression"]["risk_level"],
              result_dict["anxiety"]["risk_level"],
              result_dict["stress"]["risk_level"]]
    if "High" in levels:
        return "High"
    if "Moderate" in levels:
        return "Moderate"
    return "Low"


def _bar_svg(label: str, score: float, color: str) -> str:
    width = max(2, min(300, score * 3))  # score is 0-100 -> px scale
    return f"""
    <div style="margin-bottom:10px;">
      <div style="font-family:sans-serif;font-size:13px;margin-bottom:2px;">
        {label}: {score}/100
      </div>
      <svg width="300" height="14">
        <rect width="300" height="14" fill="#e5e7eb" rx="3"/>
        <rect width="{width}" height="14" fill="{color}" rx="3"/>
      </svg>
    </div>
    """


def summarize_conversation(user_messages: List[str], nlp_summary: Dict) -> str:
    """Lightweight, non-LLM conversation summary built from aggregate NLP
    signals plus a couple of representative excerpts. Deliberately avoids
    reproducing full user messages verbatim in the stored report beyond a
    short excerpt, and never fabricates content the user didn't say."""
    if not user_messages:
        return "No conversation content was recorded for this session."

    word_count = nlp_summary.get("avg_word_count", 0)
    sentiment = nlp_summary.get("avg_sentiment", 0.0)
    tone = "generally positive" if sentiment > 0.15 else (
        "generally negative" if sentiment < -0.15 else "mixed/neutral"
    )

    excerpt = user_messages[-1].strip()
    if len(excerpt) > 160:
        excerpt = excerpt[:157] + "..."

    return (
        f"Across {nlp_summary.get('message_count', len(user_messages))} messages "
        f"(avg. {word_count} words each), the participant's language tone was "
        f"{tone}. Their most recent reflection: \"{excerpt}\""
    )


def build_report_html(
    participant_code: str,
    session_uuid: str,
    result_dict: Dict,
    conversation_summary: str,
) -> str:
    generated_at = datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")
    overall_level = _overall_level(result_dict)
    next_steps = NEXT_STEPS_BY_LEVEL[overall_level]

    colors = {"Low": "#22c55e", "Moderate": "#f59e0b", "High": "#ef4444"}

    bars = "".join([
        _bar_svg("Depression (PHQ-9 based)", result_dict["depression"]["combined_score"],
                 colors[result_dict["depression"]["risk_level"]]),
        _bar_svg("Anxiety (GAD-7 based)", result_dict["anxiety"]["combined_score"],
                 colors[result_dict["anxiety"]["risk_level"]]),
        _bar_svg("Stress (PSS-10 based)", result_dict["stress"]["combined_score"],
                 colors[result_dict["stress"]["risk_level"]]),
        _bar_svg("Overall Wellness", result_dict["overall_wellness_score"], "#3b82f6"),
    ])

    explanations: List[str] = []
    for domain in ("depression", "anxiety", "stress"):
        explanations.extend(result_dict[domain]["explanation"])

    explanation_list = "".join(f"<li>{e}</li>" for e in explanations)

    ml_block = ""
    if result_dict.get("ml_signal"):
        ml = result_dict["ml_signal"]
        ml_block = f"""
        <h3>Secondary ML Signal</h3>
        <p style="font-size:13px;color:#555;">{ml['model_disclaimer']}</p>
        <p>Predicted risk tier: <strong>{ml['predicted_risk']}</strong></p>
        """

    return f"""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MindScreen AI Screening Report — {participant_code}</title>
</head>
<body style="font-family:sans-serif;max-width:700px;margin:40px auto;color:#111;">
  <h1 style="margin-bottom:0;">MindScreen AI — Screening Report</h1>
  <p style="color:#666;margin-top:4px;">Generated {generated_at}</p>

  <table style="width:100%;border-collapse:collapse;margin:20px 0;">
    <tr><td style="padding:4px 0;color:#666;">Participant ID</td><td>{participant_code}</td></tr>
    <tr><td style="padding:4px 0;color:#666;">Session</td><td>{session_uuid}</td></tr>
    <tr><td style="padding:4px 0;color:#666;">Confidence</td><td>{result_dict['confidence_score']}</td></tr>
  </table>

  <h2>Screening Scores</h2>
  {bars}

  <h2>AI Risk Assessment &amp; Explanation</h2>
  <ul>{explanation_list}</ul>
  {ml_block}

  <h2>Conversation Summary</h2>
  <p>{conversation_summary}</p>

  <h2>Suggested Next Steps</h2>
  <p>{next_steps}</p>

  <hr style="margin:30px 0;">
  <p style="font-size:12px;color:#666;">{DISCLAIMER}</p>
</body>
</html>"""
