#!/usr/bin/env python3
# description: Mark a plan task complete - [ ] -> - [x]; outputs remaining tasks
# Args: <plan-filename> <task-substring>
import sys, os, re

if len(sys.argv) < 3:
    print("usage: plan_check <plan-filename> <task-substring>")
    sys.exit(1)

import shutil
if os.environ.get('OLLIE_BEADS_ENABLE') == '1' and shutil.which('bd') and os.path.exists('.beads'):
    print("error: beads is available — use 'bd' for planning instead of plan_check", file=sys.stderr)
    sys.exit(2)

ollie = os.environ.get('OLLIE', os.path.expanduser('~/mnt/ollie'))
plan_dir = os.path.join(ollie, 'pl')
filepath = os.path.join(plan_dir, os.path.basename(sys.argv[1]))
substring = sys.argv[2].lower()

if not os.path.exists(filepath):
    print(f"error: plan not found: {os.path.basename(filepath)}")
    sys.exit(1)

with open(filepath) as f:
    lines = f.readlines()

matched = False
for i, line in enumerate(lines):
    if re.match(r'^- \[ \] ', line) and substring in line.lower():
        lines[i] = line.replace('- [ ] ', '- [x] ', 1)
        matched = True
        break

if not matched:
    print(f"error: no unchecked task matching {sys.argv[2]!r}")
    sys.exit(1)

with open(filepath, 'w') as f:
    f.writelines(lines)

remaining = [line[6:].strip() for line in lines if re.match(r'^- \[ \] ', line)]
if remaining:
    print('\n'.join(f'- [ ] {s}' for s in remaining))
else:
    print('all tasks checked; run plan_finish to close the plan')
