"""خادم MCP لـ Veedon — يُتيح لأي وكيل AI (Claude/Dify/…) استعلام ذكاء الفيديو كأدوات.
معيار تكامل 2026 (Model Context Protocol). يعيد استخدام منطق نقاط insights نفسه.

التشغيل: python mcp_server.py   (stdio)   — أو: mcp dev mcp_server.py
يشارك قاعدة البيانات نفسها؛ اضبط DATABASE_URL كالبوابة.
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from mcp.server.fastmcp import FastMCP           # noqa: E402
from sqlalchemy import select                    # noqa: E402

from app import analytics, escalation, insights   # noqa: E402
from app.db import SessionLocal                   # noqa: E402
from app.models import Branch, Event              # noqa: E402

mcp = FastMCP("veedon")


@mcp.tool()
def list_branches() -> list:
    """قائمة فروع Veedon (المعرّف + الاسم) — نقطة البداية لبقية الأدوات."""
    db = SessionLocal()
    try:
        return [{"id": str(b.id), "name": b.name} for b in db.scalars(select(Branch)).all()]
    finally:
        db.close()


@mcp.tool()
def branch_analytics(branch_id: str, days: int = 7) -> dict:
    """تحليلات تشغيلية للفرع: إجمالي الزوّار، الاتجاه%، ساعة الذروة، الإشغال، أنشط المناطق."""
    db = SessionLocal()
    try:
        b = db.get(Branch, branch_id)
        if not b:
            return {"error": "branch not found"}
        a = analytics.compute(db, b, days)
        return {k: a[k] for k in ("days", "total_footfall", "avg_daily_footfall",
                                  "trend_pct", "peak_hour", "avg_occupancy",
                                  "dwell_min_est", "top_zones")}
    finally:
        db.close()


@mcp.tool()
def search_events(branch_id: str, query: str) -> dict:
    """بحث بلغة طبيعية عربية عبر أحداث الفرع (مثال: «دخول المخزن بعد المغرب»)."""
    db = SessionLocal()
    try:
        return insights.nl_search({"branch_id": branch_id, "query": query}, db)
    finally:
        db.close()


@mcp.tool()
def ops_brief(branch_id: str, days: int = 7) -> dict:
    """مساعد Veedon: ملخّص تشغيلي سردي + توصيات لأحداث الفرع."""
    db = SessionLocal()
    try:
        return insights.ops_brief(branch_id, days, db)
    finally:
        db.close()


@mcp.tool()
def recent_incidents(branch_id: str, hours: int = 24) -> dict:
    """خط زمني موحّد: حوادث الفرع المتقاربة خلال الفترة."""
    db = SessionLocal()
    try:
        return insights.incidents(branch_id, hours, db)
    finally:
        db.close()


@mcp.tool()
def verified_alarm(event_id: str) -> dict:
    """حزمة الإنذار المؤكَّد (AVS-01) لحدث — مستوى + أدلة + توصية إرسال."""
    db = SessionLocal()
    try:
        return escalation.verified_alarm(event_id, db)
    finally:
        db.close()


if __name__ == "__main__":
    mcp.run()
