"""
EXAMPLE TASKS — written for the USER, not for the developer.

A port of `features/tasks/data/mock.js`, which carries the rule and the reason:
"Fill with example data" is an ONBOARDING action, so what it loads must be a
page a real person would be glad to find. The set this replaced was a stress
fixture — an empty title, a blown estimate, rows already overdue on the day
they loaded — and it read as a planner already going badly.

It still teaches. Between them the rows show one clean example of each thing a
task can carry, and the list is here so a row cannot be deleted without
noticing what went with it:

    subtasks driving progress   1, 3, 7
    a manual progress value     4
    reminders (a real moment)   1, 2
    needs focus                 1, 7
    an effort estimate + actual 1, 7
    no due date, and that is OK 5
    a task already done         6

Deliberately absent: overdue rows, blocked rows, five-tag rows, anything with
an empty field. The edge cases still matter; they are typed in by hand.

TWO DIFFERENCES FROM THE CLIENT'S SET, both forced:

- **The goal link is dropped.** `t-5` points at `g-6` on the example Goals
  page, and a goal id only means something once Phase 4 exists and once that
  page has been seeded. A pointer at nothing is worse than no pointer.
- **`actual_minutes` is included even though it is read-only on the serializer.**
  These rows are never saved by this endpoint — the client writes them back
  through `bulk` — so this is display data. The bulk write drops it, which is
  correct: logged time is a measurement, and example data has not measured
  anything.
"""

from datetime import date, datetime, timedelta

# Ids are synthetic and local to the response. Nothing is persisted here; the
# client maps them through `fromWire` and they are replaced by real ids the
# moment the set is written back through `bulk`.
def _sample(index, **fields):
    row = {
        'id': f'sample-{index}',
        'title': '',
        'notes': '',
        'status': 'todo',
        'priority': 'medium',
        'tags': [],
        'due_date': None,
        'effort_minutes': None,
        'actual_minutes': 0,
        'progress_fraction': None,
        'needs_focus': False,
        'goal': None,
        'subtasks': [],
        'reminders': [],
        'calendar_page_id': None,
        'calendar_event_id': None,
        'note_link': None,
        'recurrence': None,
        'blocked_by': [],
        'properties': {},
        'is_sample': True,
        'completed_at': None,
    }
    row.update(fields)
    return row


def _sub(title, done=False):
    return {'id': f's-{title[:12]}', 'title': title, 'done': done}


def sample_tasks(today=None):
    """
    The example set, dated relative to TODAY at request time.

    A fixture with absolute dates rots into a screen of stale rows, and every
    due date here is today or later so a freshly filled page opens with nothing
    already late.
    """
    today = today or date.today()
    now = datetime.now()

    def day(offset):
        return (today + timedelta(days=offset)).isoformat()

    def created(days_ago):
        return (now - timedelta(days=days_ago)).isoformat()

    return [
        _sample(
            1,
            title='Finish the history essay',
            notes='Two pages left. The sources are already saved in the Notes page.',
            status='in_progress',
            priority='high',
            tags=['learning', 'deep-work'],
            due_date=day(2),
            effort_minutes=180,
            actual_minutes=60,
            needs_focus=True,
            # Left null on purpose: with subtasks present, progress counts from
            # them, and ticking one moves the bar.
            reminders=[f'{day(1)}T09:00'],
            subtasks=[
                _sub('Outline the argument', True),
                _sub('Write the middle section'),
                _sub('Check the citations'),
            ],
            created_at=created(4),
        ),
        _sample(
            2,
            title='Pay the electricity bill',
            notes='Comes every month. A repeating bill is a task — habits have no due date.',
            priority='high',
            tags=['money', 'errand'],
            due_date=day(4),
            effort_minutes=10,
            reminders=[f'{day(4)}T09:00'],
            recurrence={'every': 'month', 'day': 14},  # schema-ready; no UI yet
            created_at=created(6),
        ),
        _sample(
            3,
            title='Plan the weekend trip',
            notes='Three of us going. Split the costs afterwards on the Budget page.',
            tags=['people'],
            due_date=day(6),
            effort_minutes=60,
            subtasks=[_sub('Pick the dates'), _sub('Book the train'), _sub('Share the packing list')],
            created_at=created(2),
        ),
        _sample(
            4,
            title='Set up the study corner',
            notes='Made a start on the shelf. Typing a progress number keeps the bar honest.',
            status='in_progress',
            priority='low',
            tags=['home'],
            due_date=day(9),
            effort_minutes=90,
            actual_minutes=20,
            # Typed by hand, and it wins outright over every other source.
            progress_fraction=0.25,
            created_at=created(3),
        ),
        _sample(
            5,
            title='Read two chapters',
            notes='No deadline on this one, and that is fine.',
            priority='low',
            tags=['learning'],
            effort_minutes=30,
            created_at=created(1),
        ),
        _sample(
            6,
            title='Book the dentist',
            notes='Finished last week. Kept here so the Done group is not empty on the first run.',
            status='done',
            tags=['health'],
            due_date=day(-2),
            effort_minutes=15,
            actual_minutes=15,
            subtasks=[_sub('Find the number', True), _sub('Call and pick a slot', True)],
            created_at=created(10),
            completed_at=(now - timedelta(hours=30)).isoformat(),
        ),
        _sample(
            7,
            title='Send the internship application',
            notes='CV is ready. The letter needs one quiet hour.',
            status='in_progress',
            priority='high',
            tags=['work'],
            due_date=day(3),
            effort_minutes=90,
            actual_minutes=45,
            needs_focus=True,
            subtasks=[_sub('Update the CV', True), _sub('Write the cover letter')],
            created_at=created(5),
        ),
        _sample(
            8,
            title='Water the plants',
            notes='A two-minute task belongs on the list too — it is one less thing to remember.',
            priority='low',
            tags=['home'],
            due_date=day(0),
            effort_minutes=5,
            created_at=created(1),
        ),
    ]
