"""Delete specific attempt rows (e.g. test data) and rebuild progress, daily totals and badges from what remains.
Usage (inside the container): python tools/remove_attempts.py <attempt id> [<attempt id> ...]"""
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) if os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), "db.py")) else os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import db, gamify
import curriculum as CUR

ids = [int(x) for x in sys.argv[1:]]
c = db.get_db()
rows = c.execute(f"SELECT * FROM attempts WHERE id IN ({','.join('?' * len(ids))})", ids).fetchall()
users = {r["user_id"] for r in rows}
print("deleting", [(r["id"], r["activity_id"], r["created_at"]) for r in rows])
c.execute(f"DELETE FROM attempts WHERE id IN ({','.join('?' * len(ids))})", ids)
for uid in users:
    c.execute("DELETE FROM progress WHERE user_id=?", (uid,))
    c.execute("DELETE FROM days WHERE user_id=?", (uid,))
    c.execute("DELETE FROM badges WHERE user_id=?", (uid,))
    best = {}
    for a in c.execute("SELECT * FROM attempts WHERE user_id=? ORDER BY id", (uid,)).fetchall():
        lid, act = CUR.ACTIVITIES[a["activity_id"]]
        pts = round(act["points"] * a["pct"] / 100) + (5 if a["pct"] == 100 else 0)
        b = best.setdefault(a["activity_id"], dict(lesson=a["lesson_id"], score=0, total=a["total"], pct=-1, stars=0, points=0, n=0, done=0, first=a["created_at"], last=a["created_at"]))
        if a["pct"] > b["pct"]:
            b.update(score=a["score"], total=a["total"], pct=a["pct"])
        b["stars"] = max(b["stars"], a["stars"]); b["points"] = max(b["points"], pts); b["n"] += 1; b["last"] = a["created_at"]
        b["done"] = b["done"] or int(a["pct"] >= 50)
        day = a["created_at"][:10]
        c.execute("""INSERT INTO days (user_id, day, points, activities) VALUES (?,?,?,1)
                     ON CONFLICT(user_id, day) DO UPDATE SET points=points+excluded.points, activities=activities+1""", (uid, day, a["points_earned"]))
    for aid, b in best.items():
        c.execute("""INSERT INTO progress (user_id, activity_id, lesson_id, best_score, best_total, best_pct, stars, points, attempts, completed, first_done, last_done)
                     VALUES (?,?,?,?,?,?,?,?,?,?,?,?)""", (uid, aid, b["lesson"], b["score"], b["total"], b["pct"], b["stars"], b["points"], b["n"], b["done"], b["first"], b["last"]))
    c.commit()
    st = db.stats(uid)
    for bid in gamify.check_badges(st, db.progress_map(uid), CUR.LESSONS, CUR.UNITS):
        db.award_badge(uid, bid)
    print("user", uid, "now:", db.stats(uid))
c.commit()
c.close()
