// AI Feature Risk Badge, a micro-SaaS starter on NovaCopilot (Apache 2.0).
// Takes a short description of an AI feature and returns an SVG badge plus the
// EU AI Act articles behind it. The badge never says "certified" or "compliant".
// Resale is allowed, but keep "Source: NovaCopilot" and the hash line.
const MCP = "https://legal.exploreworldai.com/api/public/mcp-open?src=starter-badge";
const UA = "novacopilot-starter/1.0 ai-feature-risk-badge";

export type NovaAnswer = { id: string; spoken_answer: string; official_url: string; source_status: string; source: string; core_sha256?: string };

async function sha256(t: string) {
  const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(t));
  return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join("");
}

export async function receipt(a: NovaAnswer) {
  return a.core_sha256 ? `core_sha256 ${a.core_sha256}` : `answer_sha256 ${await sha256(a.id + "\n" + a.spoken_answer)} (computed over the delivered answer)`;
}

/** Fixed keyword table: which AI Act articles to read. No model guesses. */
export function articlesFor(description: string) {
  const d = description.toLowerCase();
  if (/chatbot|assistant|generat|deepfake|synthetic/.test(d)) return ["50"];
  if (/cv|recruit|hiring|credit|score|biometric|exam|education/.test(d)) return ["6", "26"];
  return ["6"];
}

export async function askNova(article: string, fetcher: typeof fetch = fetch): Promise<NovaAnswer> {
  const res = await fetcher(MCP, {
    method: "POST",
    headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "user-agent": UA },
    body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "article_question", arguments: { act: "ai-act", article, lang: "en" } } }),
  });
  const raw = await res.text();
  const line = raw.split("\n").find((l) => l.startsWith("data:")) ?? raw;
  return JSON.parse(JSON.parse(line.replace(/^data:\s*/, "")).result.content[0].text);
}

export async function renderBadge(feature: string, answers: NovaAnswer[]) {
  const ids = answers.map((a) => a.id).join(", ");
  const receipts = await Promise.all(answers.map(receipt));
  const label = `EU AI Act reviewed: ${ids}`;
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="360" height="40" role="img" aria-label="${label}"><rect width="360" height="40" rx="6" fill="#0b1f3a"/><text x="12" y="17" fill="#fff" font-size="12" font-family="sans-serif">${label}</text><text x="12" y="32" fill="#9fc3e8" font-size="10" font-family="sans-serif">Source: NovaCopilot</text></svg>`;
  return { feature, svg, articles: answers.map((a) => ({ id: a.id, official_url: a.official_url, source_status: a.source_status })), receipts, note: "Review aid, not a certification and not legal advice.", source: "Source: NovaCopilot" };
}

export default {
  async fetch(request: Request): Promise<Response> {
    const feature = (new URL(request.url).searchParams.get("feature") ?? "").slice(0, 200);
    if (!feature) return new Response("Add ?feature=customer support chatbot", { status: 400 });
    const answers = await Promise.all(articlesFor(feature).map((n) => askNova(n)));
    return Response.json(await renderBadge(feature, answers));
  },
};
