#!/bin/bash
set -euo pipefail
TOKEN=$(cat ~/.todoist_token)
RESPONSE=$(curl -s "https://api.todoist.com/api/v1/tasks" \
  -H "Authorization: Bearer $TOKEN")

if [ -z "$RESPONSE" ]; then
  echo "Todoist API returned empty response."
  exit 1
fi

echo "$RESPONSE" | python3 -c "
import sys, json
from datetime import date, timedelta

data = json.load(sys.stdin)
tasks = data.get('results', [])

if not tasks:
    print('No tasks found.')
    sys.exit(0)

today_str = str(date.today())
tomorrow_str = str(date.today() + timedelta(days=1))

# All unchecked tasks (with or without due date)
unchecked = [t for t in tasks if not t.get('checked')]

if not unchecked:
    print('No unchecked tasks.')
    sys.exit(0)

# Split into due and no-due
with_due = [t for t in unchecked if t.get('due') and t['due'].get('date')]
without_due = [t for t in unchecked if not t.get('due') or not t['due'].get('date')]

# Classify due tasks
today_tasks = [t for t in with_due if t['due']['date'] == today_str]
tomorrow_tasks = [t for t in with_due if t['due']['date'] == tomorrow_str]
later_tasks = [t for t in with_due if t['due']['date'] not in (today_str, tomorrow_str)]

print(f'Todoist: {len(tasks)} total | {len(unchecked)} open | {len(with_due)} with due date | {len(without_due)} without due date')
print()

if today_tasks:
    print('📅 HEUTE:')
    for t in today_tasks:
        print(f'  • {t[\"content\"]} (fällig: {t[\"due\"][\"date\"]})')
    print()

if tomorrow_tasks:
    print('📅 MORGEN:')
    for t in tomorrow_tasks:
        print(f'  • {t[\"content\"]} (fällig: {t[\"due\"][\"date\"]})')
    print()

if later_tasks:
    print('📅 SPÄTER (fällig):')
    for t in later_tasks:
        print(f'  • {t[\"content\"]} (fällig: {t[\"due\"][\"date\"]})')
    print()

if without_due:
    print('❗ OHNE FÄLLIGKEITSDATUM:')
    for t in without_due:
        print(f'  • {t[\"content\"]} (id: {t[\"id\"]})')
    print()
"
