import 'server-only';
import fs from 'node:fs';
import path from 'node:path';
import {randomUUID} from 'node:crypto';
export type InsightKind='page_view'|'link_click'|'checkout_start'|'checkout_created'|'checkout_paid'|'larp_created';
type Event={id:string;kind:InsightKind;at:string;path?:string;destination?:string;subject?:string;uniqueKey?:string};
const file=path.join(process.cwd(),'.local-data','owner-insights.json');
function read():Event[]{try{const v=JSON.parse(fs.readFileSync(file,'utf8')) as Event[];return Array.isArray(v)?v:[]}catch{return []}}
/** Aggregated local event log; never collect payment credentials, email or IP. */
export function recordInsight(kind:InsightKind,options:{path?:string;destination?:string;subject?:string;uniqueKey?:string}={}){
 const items=read();if(options.uniqueKey&&items.some(e=>e.kind===kind&&e.uniqueKey===options.uniqueKey))return;
 const clean=(v?:string)=>typeof v==='string'?v.slice(0,180).replace(/[\r\n\t<>]/g,''):undefined;
 items.push({id:randomUUID(),kind,at:new Date().toISOString(),path:clean(options.path),destination:clean(options.destination),subject:clean(options.subject),uniqueKey:clean(options.uniqueKey)});
 fs.mkdirSync(path.dirname(file),{recursive:true});const tmp=file+'.tmp';fs.writeFileSync(tmp,JSON.stringify(items.slice(-20000)),{mode:0o600});fs.renameSync(tmp,file);
}
export function getInsightReport(days=30){
 const events=read().filter(x=>Date.parse(x.at)>=Date.now()-days*86400000);
 const kinds:InsightKind[]=['page_view','link_click','checkout_start','checkout_created','checkout_paid','larp_created'];
 const totals=Object.fromEntries(kinds.map(kind=>[kind,events.filter(e=>e.kind===kind).length]));
 const byDay:Array<{date:string;page_view:number;link_click:number;checkout_start:number;checkout_created:number;checkout_paid:number;larp_created:number}>=[];
 for(let i=days-1;i>=0;i--){const date=new Date(Date.now()-i*86400000).toISOString().slice(0,10);const same=events.filter(e=>e.at.slice(0,10)===date);byDay.push({date,page_view:same.filter(e=>e.kind==='page_view').length,link_click:same.filter(e=>e.kind==='link_click').length,checkout_start:same.filter(e=>e.kind==='checkout_start').length,checkout_created:same.filter(e=>e.kind==='checkout_created').length,checkout_paid:same.filter(e=>e.kind==='checkout_paid').length,larp_created:same.filter(e=>e.kind==='larp_created').length})}
 const destinations=[...new Set(events.filter(e=>e.kind==='link_click').map(e=>e.destination||''))].filter(Boolean).map(destination=>({destination,clicks:events.filter(e=>e.kind==='link_click'&&e.destination===destination).length})).sort((a,b)=>b.clicks-a.clicks).slice(0,12);
 return {days,totals,byDay,destinations,lastEvents:events.slice(-40).reverse().map(({id,kind,at,path,destination,subject})=>({id,kind,at,path,destination,subject}))};
}
