"""تقارير الامتثال — أقوى ورقة بيع: تحوّل أحداث الجهاز إلى تقرير مؤرّخ بأدلة
مصوّرة، مربوط بالجهة الرقابية السعودية لكل قطاع. HTML عربي RTL قابل للطباعة PDF.
"""

from datetime import timedelta

from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import HTMLResponse
from sqlalchemy import select
from sqlalchemy.orm import Session

from .db import get_db
from .models import Branch, Camera, Event, EventType, utcnow

router = APIRouter(prefix="/reports", tags=["reports"])

# القطاع → الجهة الرقابية السعودية (زاوية البيع القاتلة)
REGULATOR = {
    "restaurant": "البلدية + الهيئة العامة للغذاء والدواء (SFDA)",
    "factory": "الهيئة العليا للأمن الصناعي (HCIS) + SFDA",
    "education": "وزارة التعليم",
    "health": "وزارة الصحة + المركز السعودي لاعتماد المنشآت الصحية (CBAHI)",
    "farm": "الهيئة العامة للغذاء والدواء (SFDA)",
    "hotel": "وزارة السياحة + البلدية (وزارة الشؤون البلدية والقروية والإسكان)",
    "retail": "البلدية + وزارة التجارة",
    "mosque": "وزارة الشؤون الإسلامية + الحج والعمرة + الدفاع المدني (SDAIA)",
    "warehouse": "الدفاع المدني + الهيئة العامة للنقل (HCIS للمواد الخطرة)",
    "kids": "البلدية + الهيئة العامة للترفيه (GEA) + الدفاع المدني",
    "sports": "وزارة الرياضة + الدفاع المدني + الأمن العام",
    "general": "اشتراطات السلامة العامة",
}

# ربط ميزات التعليم ببنود اشتراطات وزارة التعليم للأمن والسلامة المدرسية
MOE_DOMAINS = {
    "الأمن والحماية من التهديدات": ["weapon_detection", "emergency_lockdown",
                                     "visitor_unknown", "after_hours_intrusion",
                                     "wrong_direction", "perimeter_intrusion"],
    "السلوك ومكافحة العنف والتنمّر": ["fight_detection", "bullying"],
    "الصحة والسلامة الجسدية": ["stair_fall", "student_sleeping", "vape_detection",
                                "smoking", "patient_fall"],
    "تنظيم الدخول والحضور": ["gate_attendance", "restricted_zone", "crowding",
                              "queue_count", "entry_exit_count"],
}


def branch_sector(db: Session, branch: Branch) -> str:
    """قطاع الفرع = أكثر قطاع للمزايا المفعّلة على كاميراته (تقريب عملي)."""
    counts = {}
    for cam in branch.cameras:
        for a in cam.assignments:
            if a.enabled and a.event_type.feature_key:
                s = a.event_type.sector or "general"
                counts[s] = counts.get(s, 0) + 1
    non_general = {k: v for k, v in counts.items() if k != "general"}
    pool = non_general or counts
    return max(pool, key=pool.get) if pool else "general"


@router.get("/branch/{branch_id}", response_class=HTMLResponse)
def branch_report(branch_id: str, days: int = 30, db: Session = Depends(get_db)):
    branch = db.get(Branch, branch_id)
    if not branch:
        raise HTTPException(404, "branch not found")
    since = utcnow() - timedelta(days=days)
    cam_ids = [c.id for c in branch.cameras]
    events = []
    if cam_ids:
        events = db.scalars(
            select(Event).where(Event.camera_id.in_(cam_ids),
                                Event.detected_at >= since)
            .order_by(Event.detected_at.desc())).all()
    names = {et.feature_key: et.name_ar for et in db.scalars(select(EventType)).all()}

    # تجميع حسب الميزة + عدّ المخالفات (severity=high)
    by_feature: dict[str, dict] = {}
    for e in events:
        f = by_feature.setdefault(e.event_type, {"total": 0, "violations": 0, "samples": []})
        f["total"] += 1
        if e.severity == "high":
            f["violations"] += 1
        if e.snapshot_url and len(f["samples"]) < 4:
            f["samples"].append(e)

    violations = sum(f["violations"] for f in by_feature.values())
    # ponytail: درجة تقريبية — 100 ناقص وزن المخالفات، بحد أدنى 0. يُعاير لاحقاً بالمعدّل/الفرع.
    score = max(0, 100 - min(100, violations * 3))
    sector = branch_sector(db, branch)
    org = branch.organization.name if branch.organization else "—"
    # مزايا مفعّلة على كاميرات الفرع (لتحديد التغطية مقابل بنود الجهة)
    enabled_keys = {a.event_type.feature_key for cam in branch.cameras
                    for a in cam.assignments
                    if a.enabled and a.event_type.feature_key}
    moe_html = _moe_block(enabled_keys, by_feature, names) if sector == "education" else ""
    return HTMLResponse(_render(branch, org, sector, days, score, violations,
                                len(events), by_feature, names, moe_html))


def _moe_block(enabled_keys, by_feature, names) -> str:
    """جدول بنود اشتراطات وزارة التعليم: التغطية + المخالفات المرصودة لكل مجال."""
    rows = ""
    for domain, keys in MOE_DOMAINS.items():
        covered = [k for k in keys if k in enabled_keys]
        viol = sum(by_feature.get(k, {}).get("violations", 0) for k in keys)
        status = ("✅ مغطّى" if covered else "⚠️ غير مفعّل")
        color = "#0b7a4b" if covered else "#9a6700"
        items = "، ".join(names.get(k, k) for k in covered) or "لا مزايا مفعّلة"
        rows += f"""<tr>
          <td><b>{domain}</b><div class="muted">{items}</div></td>
          <td style="text-align:center;color:{color};font-weight:700">{status}</td>
          <td style="text-align:center;color:#c0392b;font-weight:700">{viol}</td></tr>"""
    return f"""<h2 style="margin-top:22px">اشتراطات وزارة التعليم للأمن والسلامة المدرسية</h2>
    <table><thead><tr><th>المجال</th><th>حالة التغطية</th><th>مخالفات الفترة</th></tr></thead>
    <tbody>{rows}</tbody></table>
    <p class="muted">مصفوفة تغطية آلية مقابل مجالات الأمن والسلامة والصحة المدرسية —
    دليل جاهز لزيارة المشرف/التقييم الذاتي.</p>"""


def _badge(score: int) -> tuple[str, str]:
    if score >= 85:
        return "#0b7a4b", "ملتزم"
    if score >= 60:
        return "#9a6700", "يحتاج تحسيناً"
    return "#c0392b", "غير ملتزم"


def _render(branch, org, sector, days, score, violations, total, by_feature, names,
            extra_html=""):
    color, label = _badge(score)
    rows = ""
    for key, f in sorted(by_feature.items(), key=lambda kv: -kv[1]["violations"]):
        thumbs = "".join(
            f'<img src="{e.snapshot_url}" class="thumb">' for e in f["samples"])
        rows += f"""<tr>
          <td>{names.get(key, key)}</td>
          <td style="text-align:center">{f['total']}</td>
          <td style="text-align:center;color:#c0392b;font-weight:700">{f['violations']}</td>
          <td>{thumbs or '—'}</td></tr>"""
    if not rows:
        rows = '<tr><td colspan="4" style="text-align:center;color:#6b7280">لا أحداث في الفترة</td></tr>'
    date = utcnow().strftime("%Y-%m-%d")
    return f"""<!doctype html><html lang="ar" dir="rtl"><head><meta charset="utf-8">
<title>تقرير امتثال — {branch.name}</title><style>
  body{{font-family:'Segoe UI',Tahoma,Arial;color:#1f2937;max-width:900px;margin:24px auto;padding:0 16px}}
  .head{{display:flex;justify-content:space-between;align-items:flex-start;border-bottom:3px solid #0f4c81;padding-bottom:12px}}
  .logo{{font-size:26px;font-weight:800;color:#0f4c81}} .logo span{{color:#16a085}}
  h1{{font-size:20px;margin:16px 0 4px}} .muted{{color:#6b7280;font-size:13px}}
  .score{{display:inline-block;border:3px solid {color};color:{color};border-radius:12px;
    padding:10px 22px;font-size:20px;font-weight:800;margin:12px 0}}
  .reg{{background:#eef4fb;border-right:4px solid #0f4c81;padding:10px 14px;border-radius:8px;margin:12px 0}}
  table{{width:100%;border-collapse:collapse;margin-top:12px}}
  th{{background:#0f4c81;color:#fff;padding:9px;font-size:13px;text-align:right}}
  td{{border-bottom:1px solid #e3e8ef;padding:9px;font-size:14px;vertical-align:middle}}
  .thumb{{height:46px;border-radius:5px;border:1px solid #e3e8ef;margin-left:4px}}
  .foot{{margin-top:24px;color:#6b7280;font-size:12px;border-top:1px solid #e3e8ef;padding-top:10px}}
  @media print{{.noprint{{display:none}}}}
</style></head><body>
<div class="head">
  <div><div class="logo">Veedon<span>.ai</span></div><div class="muted">تقرير الامتثال التشغيلي</div></div>
  <div class="muted">تاريخ التقرير: {date}<br>الفترة: آخر {days} يوماً</div>
</div>
<h1>{org} — {branch.name}</h1>
<div class="reg"><b>الجهة الرقابية:</b> {REGULATOR.get(sector, REGULATOR['general'])}
  &nbsp;|&nbsp; <b>القطاع:</b> {sector}</div>
<div class="score">درجة الالتزام: {score}/100 — {label}</div>
<p class="muted">إجمالي الأحداث المرصودة: {total} &nbsp;|&nbsp; المخالفات (تحتاج إجراء): {violations}</p>
<table><thead><tr><th>بند المراقبة</th><th>مرصود</th><th>مخالفات</th><th>أدلة مصوّرة</th></tr></thead>
<tbody>{rows}</tbody></table>
{extra_html}
<button class="noprint" onclick="window.print()"
  style="margin-top:16px;background:#0f4c81;color:#fff;border:none;border-radius:8px;padding:10px 20px;cursor:pointer">
  طباعة / حفظ PDF</button>
<div class="foot">تقرير آلي من منصة Veedon.ai — الأدلة مؤرّخة ومحفوظة وفق سياسة الاحتفاظ.
  هذا التقرير مؤشّر تشغيلي مساعد ولا يُغني عن التفتيش الرسمي.</div>
</body></html>"""
