// Task Team — Activity Monitor — 2026-03-30
async function activityRoutes(app) {
    await app.db.query(`
        CREATE TABLE IF NOT EXISTS activity_logs (
            id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
            user_id UUID REFERENCES users(id) ON DELETE CASCADE,
            app_name VARCHAR(255) NOT NULL,
            package_name VARCHAR(255),
            duration_seconds INTEGER DEFAULT 0,
            category VARCHAR(50),
            recorded_at TIMESTAMPTZ DEFAULT NOW(),
            device VARCHAR(100)
        );
        CREATE INDEX IF NOT EXISTS idx_activity_user ON activity_logs(user_id, recorded_at DESC);
    `).catch(() => {});

    // Report activity from phone
    app.post("/activity/report", async (req) => {
        const { user_id, activities } = req.body;
        // activities: [{app_name, package_name, duration_seconds, category}]
        let inserted = 0;
        for (const a of (activities || [])) {
            await app.db.query(
                "INSERT INTO activity_logs (user_id, app_name, package_name, duration_seconds, category, device) VALUES ($1,$2,$3,$4,$5,$6)",
                [user_id, a.app_name, a.package_name || "", a.duration_seconds || 0, a.category || "other", a.device || "android"]
            );
            inserted++;
        }
        return { status: "ok", inserted };
    });

    // Get activity summary
    app.get("/activity/summary", async (req) => {
        const { user_id, days } = req.query;
        const d = parseInt(days) || 7;
        const { rows } = await app.db.query(`
            SELECT category, sum(duration_seconds) as total_seconds, count(*) as sessions
            FROM activity_logs
            WHERE user_id = $1 AND recorded_at > NOW() - make_interval(days => $2)
            GROUP BY category ORDER BY total_seconds DESC
        `, [user_id, d]);
        return { data: rows };
    });

    // Get daily breakdown
    app.get("/activity/daily", async (req) => {
        const { user_id } = req.query;
        const { rows } = await app.db.query(`
            SELECT date_trunc('day', recorded_at)::date as day,
                   sum(duration_seconds) as total_seconds,
                   count(DISTINCT app_name) as apps_used
            FROM activity_logs WHERE user_id = $1 AND recorded_at > NOW() - INTERVAL '7 days'
            GROUP BY 1 ORDER BY 1
        `, [user_id]);
        return { data: rows };
    });

    // AI analysis of activity vs planned tasks
    app.get("/activity/ai-analysis", async (req) => {
        const { user_id } = req.query;
        const { rows: activities } = await app.db.query(
            `SELECT app_name, category, sum(duration_seconds) as total FROM activity_logs
             WHERE user_id=$1 AND recorded_at > NOW() - INTERVAL '7 days' GROUP BY 1,2 ORDER BY total DESC LIMIT 10`,
            [user_id]
        );
        const { rows: tasks } = await app.db.query(
            "SELECT title, status, group_id FROM tasks WHERE user_id=$1 ORDER BY created_at DESC LIMIT 10",
            [user_id]
        );

        if (!activities.length) return { data: { message: "No activity data yet" } };

        const Anthropic = require("@anthropic-ai/sdk");
        const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
        const response = await anthropic.messages.create({
            model: "claude-sonnet-4-20250514",
            max_tokens: 512,
            system: "Analyzuj pouzivani telefonu vs planovane ukoly. Odpovez cesky, strucne.",
            messages: [{ role: "user", content: `Aktivity: ${JSON.stringify(activities)}\nUkoly: ${JSON.stringify(tasks)}\nAnalyzuj: jsou aktivity v souladu s ukoly?` }]
        });
        return { data: { analysis: response.content[0].text, activities, tasks } };
    });
}

module.exports = activityRoutes;
