"""Planner endpoints."""

from __future__ import annotations

from datetime import datetime

from aiohttp import web


async def handle_planner_today(request: web.Request) -> web.Response:
    """GET /planner/today — Get today's plan."""
    store = request.app["store"]
    tz_name = request.query.get("timezone", "America/Los_Angeles")
    from zoneinfo import ZoneInfo
    tz = ZoneInfo(tz_name)
    today = datetime.now(tz).strftime("%Y-%m-%d")
    plan = await store.get_plan_for_date(today)
    if plan is None:
        return web.json_response({"plan": None, "date": today})
    return web.json_response({"plan": plan.to_dict(), "date": today})


async def handle_planner_generate(request: web.Request) -> web.Response:
    """POST /planner/generate — Generate a new daily plan."""
    body = await request.json()
    store = request.app["store"]

    from zoneinfo import ZoneInfo

    from dobby.core.planner import PlannerEngine, PlannerPrefs

    tz_name = body.get("timezone", "America/Los_Angeles")
    tz = ZoneInfo(tz_name)
    date = body.get("date", datetime.now(tz).strftime("%Y-%m-%d"))

    # Load user preferences
    prefs_data = await store.search_memories(type="preference")
    planner_prefs = PlannerPrefs.from_preferences(prefs_data) if prefs_data else PlannerPrefs()

    engine = PlannerEngine(planner_prefs)
    plan = engine.generate_plan(
        date=date,
        tz_name=tz_name,
        calendar_events=body.get("calendar_events", []),
        projects=body.get("projects", []),
        todos=body.get("todos", []),
    )

    await store.store_daily_plan(plan)
    return web.json_response(plan.to_dict(), status=201)


async def handle_planner_settings(request: web.Request) -> web.Response:
    """GET /planner/settings — Get current planner preferences."""
    store = request.app["store"]
    prefs_data = await store.search_memories(type="preference")
    planner_prefs = []
    for p in (prefs_data or []):
        key = p.get("key", "")
        if key.startswith("pref:planner-"):
            planner_prefs.append(p)

    from dobby.core.planner import PlannerPrefs
    prefs = PlannerPrefs.from_preferences(planner_prefs) if planner_prefs else PlannerPrefs()
    return web.json_response({
        "preferences": {
            "work_start": prefs.work_start,
            "work_end": prefs.work_end,
            "min_focus_minutes": prefs.min_focus_minutes,
            "break_minutes": prefs.break_minutes,
            "break_every_minutes": prefs.break_every_minutes,
            "lunch_start": prefs.lunch_start,
            "lunch_minutes": prefs.lunch_minutes,
            "buffer_before_meeting": prefs.buffer_before_meeting,
            "planner_time": prefs.planner_time,
            "calendar_ids": prefs.calendar_ids,
            "create_events": prefs.create_events,
            "post_to_slack": prefs.post_to_slack,
        },
        "raw": planner_prefs,
    })
