import {type DB,all,one,expireClaims} from './commons.ts';
export function statusLabel(t:any){if(t.moderation_status==='pending')return 'Pending';if(t.moderation_status==='quarantined')return 'Closed / quarantined';if(t.expires_at&&t.expires_at<new Date().toISOString()&&t.status!=='completed')return 'Expired';return ({open:'Open',claimed:'Being worked on',in_progress:'Being worked on',submitted:'Needs review',verified:'Needs review',completed:'Solved',disputed:'Disputed',closed:'Closed'} as Record<string,string>)[t.status]||t.status;}
export const trophyWhere=`t.moderation_status='approved' AND t.status='completed' AND a.demo=0 AND producer.demo=0 AND EXISTS(SELECT 1 FROM verifications v JOIN agents reviewer ON reviewer.id=v.author WHERE v.result_id=r.id AND v.verdict='agree' AND reviewer.demo=0) AND NOT EXISTS(SELECT 1 FROM verifications v WHERE v.result_id=r.id AND v.verdict='dispute')`;
export async function trophies(db:DB,category='',limit=100,offset=0){if(typeof category!=='string')category='';return all(db,`SELECT t.*,r.content,r.evidence,r.author,producer.name AS author_name FROM tasks t JOIN results r ON r.id=t.accepted_result_id JOIN agents a ON a.id=t.creator JOIN agents producer ON producer.id=r.author WHERE ${trophyWhere} ${category?"AND json_extract(t.protocol,'$.category')=?":""} ORDER BY t.updated_at DESC LIMIT ? OFFSET ?`,...(category?[category]:[]),limit,offset);}
export async function publicProblems(db:DB,q:Record<string,string|undefined>){q=Object.fromEntries(Object.entries(q).filter(([,v])=>typeof v==='string'));await expireClaims(db);const where=["t.moderation_status='approved'","a.demo=0"],args:any[]=[];const status=q.status||'open';if(status!=='all'){const values=status==='working'?['claimed','in_progress']:status==='review'?['submitted','verified']:status==='solved'?['completed']:[status];where.push('t.status IN ('+values.map(()=>'?').join(',')+')');args.push(...values)}
 for(const key of ['category','difficulty'])if(q[key]){where.push("json_extract(t.protocol,'$."+key+"')=?");args.push(q[key])}if(q.minutes){const minutes=Number(q.minutes);if([5,15,20,30,45,60].includes(minutes)){where.push("json_extract(t.protocol,'$.estimated_minutes')<=?");args.push(minutes)}}if(q.capability){where.push('EXISTS(SELECT 1 FROM json_each(t.required_capabilities) WHERE lower(value)=lower(?))');args.push(q.capability.slice(0,64))}
 if(status==='open'){where.push("(json_extract(t.protocol,'$.expires_at') IS NULL OR json_extract(t.protocol,'$.expires_at')>?)");args.push(new Date().toISOString())}
 return all(db,'SELECT t.* FROM tasks t JOIN agents a ON a.id=t.creator WHERE '+where.join(' AND ')+' ORDER BY t.created_at DESC,t.id DESC LIMIT 100',...args);}
export async function publicTask(db:DB,id:string){if(!/^[0-9a-f-]{36}$/i.test(id))return null;return one(db,'SELECT t.*,a.name AS creator_name,a.demo FROM tasks t JOIN agents a ON a.id=t.creator WHERE t.id=?',id);}

export async function solvedTask(db:DB,id:string){return one(db,`SELECT t.* FROM tasks t JOIN results r ON r.id=t.accepted_result_id JOIN agents a ON a.id=t.creator JOIN agents producer ON producer.id=r.author WHERE ${trophyWhere} AND t.id=?`,id);}
