#!/usr/bin/env python3
# description: Mark a plan step complete; returns remaining steps
# Args: <plan-file> <step-substring>
import sys, os, re

if len(sys.argv) < 3:
    print("usage: task_complete <plan-file> <step-substring>", file=sys.stdout)
    sys.exit(1)

ollie = os.environ.get('OLLIE', os.path.expanduser('~/mnt/ollie'))
plan_dir = os.path.join(ollie, 'pl')

# Accept either a bare filename or a path; always resolve against plan_dir
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 file not found: {filepath}", file=sys.stdout)
    sys.exit(1)

try:
    with open(filepath) as f:
        lines = f.readlines()
except OSError as e:
    print(f"error: {e}", file=sys.stdout)
    sys.exit(1)

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"no unchecked step matching {sys.argv[2]!r}", file=sys.stdout)
    sys.exit(1)

remaining = [line[6:].strip() for line in lines if re.match(r'^- \[ \] ', line)]

def restat(path, status):
    return re.sub(r'__(todo|wip|complete)\.md$', f'__{status}.md', path)

if '__todo' in filepath:
    newpath = restat(filepath, 'wip')
elif not remaining and '__wip' in filepath:
    newpath = restat(filepath, 'complete')
else:
    newpath = filepath

try:
    with open(filepath, 'w') as f:
        f.writelines(lines)
except OSError as e:
    print(f"error: failed to write {filepath}: {e}", file=sys.stdout)
    sys.exit(1)

if newpath != filepath:
    try:
        os.rename(filepath, newpath)
    except OSError as e:
        print(f"error: failed to rename to {newpath}: {e}", file=sys.stdout)
        sys.exit(1)

if remaining:
    print('\n'.join(f'- {s}' for s in remaining))
else:
    print('all steps complete')
