#!/usr/bin/env python3
# description: Check off a task in the session plan by number (1-indexed), or the first unchecked task
# Args: [n]

import sys
import os

sid = os.environ.get("OLLIE_SESSION_ID", "")
if not sid:
    print("error: OLLIE_SESSION_ID not set", file=sys.stderr)
    sys.exit(1)

ollie = os.environ.get("OLLIE", os.path.expanduser("~/mnt/ollie"))
plan_path = os.path.join(ollie, "s", sid, "plan")

try:
    content = open(plan_path).read()
except FileNotFoundError:
    print("error: no plan found", file=sys.stderr)
    sys.exit(1)

lines = content.splitlines(keepends=True)
tasks = [(i, l) for i, l in enumerate(lines) if l.startswith("- [ ]") or l.startswith("- [x]")]

if not tasks:
    print("no tasks in plan")
    sys.exit(0)

n = int(sys.argv[1]) - 1 if len(sys.argv) > 1 else None

if n is None:
    # First unchecked
    target = next(((i, l) for i, l in tasks if l.startswith("- [ ]")), None)
    if target is None:
        print("all tasks already checked")
        sys.exit(0)
else:
    if n < 0 or n >= len(tasks):
        print(f"error: task {n+1} out of range (1-{len(tasks)})", file=sys.stderr)
        sys.exit(1)
    target = tasks[n]

idx, line = target
lines[idx] = line.replace("- [ ]", "- [x]", 1)
open(plan_path, "w").write("".join(lines))
print(f"checked: {lines[idx].rstrip()}")
