// Task Team — AI Daily Briefing
const Anthropic = require("@anthropic-ai/sdk");

async function aiBriefingFeature(app) {
    const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

    app.get("/briefing/:userId", async (req) => {
        const { rows: tasks } = await app.db.query(
            "SELECT title, status, priority, due_at, group_id FROM tasks WHERE user_id=$1 AND status NOT IN ('done','completed','cancelled') ORDER BY priority DESC, due_at ASC NULLS LAST LIMIT 20",
            [req.params.userId]
        );
        const { rows: goals } = await app.db.query(
            "SELECT title, progress_pct FROM goals WHERE user_id=$1 LIMIT 5", [req.params.userId]
        );
        const { rows: reviews } = await app.db.query(
            "SELECT count(*) as due FROM review_items WHERE user_id=$1 AND next_review <= NOW()", [req.params.userId]
        );

        const response = await anthropic.messages.create({
            model: "claude-sonnet-4-20250514",
            max_tokens: 512,
            system: "Jsi osobni asistent. Dej strucny ranni briefing v cestine. Bud prakticky a motivujici.",
            messages: [{ role: "user", content: `Ranni briefing pro uzivatele:\nUkoly (${tasks.length}): ${JSON.stringify(tasks.slice(0,5).map(t=>t.title))}\nCile: ${JSON.stringify(goals.map(g=>g.title+" "+g.progress_pct+"%"))}\nKarty k opakovani: ${reviews[0]?.due || 0}\nDnes je ${new Date().toLocaleDateString("cs-CZ",{weekday:"long",day:"numeric",month:"long"})}` }]
        });
        return { data: { briefing: response.content[0].text, tasks_count: tasks.length, reviews_due: parseInt(reviews[0]?.due || 0) } };
    });
}
module.exports = aiBriefingFeature;
