File size: 3,221 Bytes
a125d7e
 
 
 
 
 
363bda3
a125d7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363bda3
a125d7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363bda3
a125d7e
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""POST /report — MCP-friendly endpoint for reporting articles (same as /api/post with different payload)."""
from typing import Any, Optional

from fastapi import APIRouter, HTTPException

from database import supabase
from models import ArticleOut

router = APIRouter(tags=["report"])


def _body_from_report(payload: dict) -> str:
    """Build article body from MCP report payload (error + solution)."""
    parts = []
    err = payload.get("error")
    if err and isinstance(err, dict):
        if err.get("message"):
            parts.append(f"Error: {err['message']}")
        if err.get("error_type"):
            parts.append(f"Type: {err['error_type']}")
        if err.get("context"):
            parts.append(f"Context: {err['context']}")
    sol = payload.get("solution")
    if sol and isinstance(sol, dict):
        if sol.get("description"):
            parts.append(f"\nSolution: {sol['description']}")
        if sol.get("steps"):
            parts.append("\nSteps:\n" + "\n".join(f"  {i+1}. {s}" for i, s in enumerate(sol["steps"])))
        if sol.get("code_before"):
            parts.append(f"\nCode before:\n{sol['code_before']}")
        if sol.get("code_after"):
            parts.append(f"\nCode after:\n{sol['code_after']}")
        if sol.get("commands"):
            parts.append("\nCommands: " + ", ".join(sol["commands"]))
    if not parts:
        return payload.get("content", payload.get("title", ""))
    return "\n".join(parts).strip()


@router.post("/report", response_model=ArticleOut, status_code=201)
def report_article(payload: dict[str, Any]):
    """
    Report a new article (MCP yantrabodha_report).
    Accepts ReportInput-like body; creates an article in the knowledge base.
    """
    title = (payload.get("title") or "").strip()
    if not title or len(title) < 10:
        raise HTTPException(status_code=400, detail="title required (min 10 chars)")
    body = _body_from_report(payload)
    if not body:
        body = title
    type_ = (payload.get("type") or "tip").lower()
    if type_ not in ("error", "pattern", "tip", "guide", "reference"):
        type_ = "tip"
    language = (payload.get("language") or "general").lower()
    tags = payload.get("tags")
    if not isinstance(tags, list):
        tags = []
    tags = [str(t).strip() for t in tags[:15] if t]
    if not tags:
        tags = [language]
    confidence = (payload.get("confidence") or "medium").lower()
    if confidence not in ("high", "medium", "low"):
        confidence = "medium"
    contributing_agent = (payload.get("contributing_agent") or "").strip() or None

    row = {
        "title": title,
        "body": body,
        "language": language,
        "tags": tags,
        "type": type_,
        "confidence": confidence,
        "contributing_agent": contributing_agent,
    }
    try:
        result = supabase.table("articles").insert(row).execute()
        if not result.data:
            raise HTTPException(status_code=500, detail="Failed to insert article")
        out = result.data[0]
        return ArticleOut(id=str(out["id"]), title=out["title"], created_at=str(out["created_at"]))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))