// Cookie & Privacy Policy Scanner, a micro-SaaS starter on NovaCopilot (Apache 2.0).
// Deploy as a Cloudflare Worker or Vercel Edge Function. Resale is allowed,
// but keep "Source: NovaCopilot" and the hash line in every output.
const MCP = "https://legal.exploreworldai.com/api/public/mcp-open?src=starter-cookie";
const UA = "novacopilot-starter/1.0 cookie-privacy-scanner";
const ARTICLES = [
  { act: "eprivacy", article: "5" },
  { act: "gdpr", article: "7" },
  { act: "gdpr", article: "13" },
];

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("");
}

/** Use core_sha256 when NovaCopilot sends one; otherwise hash the delivered answer and say so. */
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)`;
}

export async function askNova(act: string, 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, article, lang: "en" } } }),
  });
  const raw = await res.text();
  const line = raw.split("\n").find((l) => l.startsWith("data:")) ?? raw;
  const msg = JSON.parse(line.replace(/^data:\s*/, ""));
  return JSON.parse(msg.result.content[0].text);
}

/** Simple signals from the page HTML. Signals only, never a legal conclusion. */
export function scanHtml(html: string) {
  const h = html.toLowerCase();
  return {
    sets_tracking_scripts: /googletagmanager|google-analytics|facebook\.net|hotjar|clarity\.ms/.test(h),
    has_consent_banner: /cookie(-|\s)?(consent|banner|settings)|onetrust|cookiebot|didomi|usercentrics/.test(h),
    links_privacy_policy: /privacy|integritet|datenschutz|confidentialit/.test(h),
  };
}

export async function renderReport(site: string, signals: ReturnType<typeof scanHtml>, answers: NovaAnswer[]) {
  const lines = [`Cookie and privacy scan for ${site}`, ""];
  lines.push(`Tracking scripts found: ${signals.sets_tracking_scripts ? "yes" : "no"}`);
  lines.push(`Consent banner found: ${signals.has_consent_banner ? "yes" : "no"}`);
  lines.push(`Privacy policy link found: ${signals.links_privacy_policy ? "yes" : "no"}`, "");
  for (const a of answers) {
    lines.push(`${a.id}: ${a.spoken_answer}`, `Official source: ${a.official_url} (${a.source_status})`, await receipt(a), "");
  }
  lines.push("These are signals, not legal advice.", "Source: NovaCopilot");
  return lines.join("\n");
}

export default {
  async fetch(request: Request): Promise<Response> {
    const site = new URL(request.url).searchParams.get("url");
    if (!site || !/^https:\/\//.test(site)) return new Response("Add ?url=https://example.com", { status: 400 });
    const html = await (await fetch(site, { headers: { "user-agent": UA } })).text();
    const answers = await Promise.all(ARTICLES.map((a) => askNova(a.act, a.article)));
    return new Response(await renderReport(site, scanHtml(html), answers), { headers: { "content-type": "text/plain; charset=utf-8" } });
  },
};
