#!/usr/bin/env python3
"""
Helper script for Echo to update kanban tasks.
Usage: python3 update_task.py <action> <args>

Actions:
  add <column> <title> [description] [priority]
  move <task_id> <to_column>
  done <task_id>
  list
"""

import json
import sys
from datetime import datetime
from pathlib import Path

TASKS_FILE = Path(__file__).parent / 'tasks.json'

def load_tasks():
    with open(TASKS_FILE, 'r') as f:
        return json.load(f)

def save_tasks(data):
    data['lastUpdated'] = datetime.utcnow().isoformat() + 'Z'
    with open(TASKS_FILE, 'w') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)

def get_next_id(data):
    max_id = 0
    for col in data['columns']:
        for task in col['tasks']:
            num = int(task['id'].split('-')[1])
            if num > max_id:
                max_id = num
    return f"task-{max_id + 1:03d}"

def add_task(column_id, title, description="", priority="medium"):
    data = load_tasks()
    new_task = {
        "id": get_next_id(data),
        "title": title,
        "description": description,
        "created": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
        "priority": priority
    }
    
    for col in data['columns']:
        if col['id'] == column_id:
            col['tasks'].append(new_task)
            save_tasks(data)
            print(f"Added: {new_task['id']} - {title}")
            return
    
    print(f"Column not found: {column_id}")

def move_task(task_id, to_column):
    data = load_tasks()
    task = None
    
    # Find and remove task
    for col in data['columns']:
        for t in col['tasks']:
            if t['id'] == task_id:
                task = t
                col['tasks'].remove(t)
                break
        if task:
            break
    
    if not task:
        print(f"Task not found: {task_id}")
        return
    
    # Add to new column
    if to_column == 'done':
        task['completed'] = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
    
    for col in data['columns']:
        if col['id'] == to_column:
            col['tasks'].append(task)
            save_tasks(data)
            print(f"Moved: {task_id} -> {to_column}")
            return
    
    print(f"Column not found: {to_column}")

def done_task(task_id):
    move_task(task_id, 'done')

def list_tasks():
    data = load_tasks()
    for col in data['columns']:
        print(f"\n{col['name']} ({len(col['tasks'])})")
        print("-" * 40)
        for task in col['tasks']:
            print(f"  [{task['id']}] {task['title']}")

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print(__doc__)
        sys.exit(1)
    
    action = sys.argv[1]
    
    if action == 'add' and len(sys.argv) >= 4:
        add_task(
            sys.argv[2],  # column
            sys.argv[3],  # title
            sys.argv[4] if len(sys.argv) > 4 else "",
            sys.argv[5] if len(sys.argv) > 5 else "medium"
        )
    elif action == 'move' and len(sys.argv) >= 4:
        move_task(sys.argv[2], sys.argv[3])
    elif action == 'done' and len(sys.argv) >= 3:
        done_task(sys.argv[2])
    elif action == 'list':
        list_tasks()
    else:
        print(__doc__)
