"""Drive reconciliation helpers for consent-gated proactive observations.

When ``drive_action_cycle`` surfaces an observation it defers the linked drive
(``awaiting_consent``). Approve/dismiss/kanban-terminal paths must update that
drive or the same work resurfaces after ``defer_until`` expires.
"""

from __future__ import annotations

import logging

_log = logging.getLogger(__name__)

_DRIVE_ACTION_DEDUPE_PREFIX = "drive_action:"


def drive_id_from_observation_entry(item: dict) -> str:
    """Extract linked drive id from an observation queue row, if any."""
    if not isinstance(item, dict):
        return ""
    from utils.proactive_queue import observation_payload_from_entry

    obs = observation_payload_from_entry(item)
    dedupe = str(obs.get("dedupe_key") or item.get("dedupe_key") or "").strip()
    if dedupe.startswith(_DRIVE_ACTION_DEDUPE_PREFIX):
        return dedupe.split(":", 1)[1].strip()
    return ""


def _drives_cfg_int(key: str, default: int) -> int:
    try:
        from drive_engine import _get_drives_config

        return max(1, int(_get_drives_config().get(key, default)))
    except Exception:
        return default


def defer_linked_drive_after_observation_dismiss(
    drive_id: str,
    *,
    workspace: str | None = None,
) -> tuple[bool, str]:
    """Backoff a linked drive after the user dismisses the observation."""
    if not drive_id:
        return False, "no drive_id"
    from drive_engine import defer_drive

    minutes = _drives_cfg_int("observation_dismiss_defer_minutes", 10_080)
    return defer_drive(
        drive_id,
        defer_minutes=minutes,
        outcome="user_dismissed_observation",
        summary="User dismissed the proactive suggestion.",
        workspace=workspace,
    )


def defer_linked_drive_after_in_thread_approve(
    drive_id: str,
    *,
    proposed: str = "",
    workspace: str | None = None,
) -> tuple[bool, str]:
    """Backoff a linked drive while in-thread approved work runs."""
    if not drive_id:
        return False, "no drive_id"
    from drive_engine import defer_drive

    minutes = _drives_cfg_int("approved_in_thread_defer_minutes", 2_880)
    summary = f"User approved in-thread: {(proposed or 'carry out approved work')[:200]}"
    return defer_drive(
        drive_id,
        defer_minutes=minutes,
        outcome="approved_in_thread",
        summary=summary,
        workspace=workspace,
    )


def defer_linked_drive_after_observation_discuss(
    drive_id: str,
    *,
    workspace: str | None = None,
) -> tuple[bool, str]:
    """Backoff a linked drive after the user opens Discuss (not approve/dismiss)."""
    if not drive_id:
        return False, "no drive_id"
    from drive_engine import defer_drive

    minutes = _drives_cfg_int("observation_discuss_defer_minutes", 2_880)
    return defer_drive(
        drive_id,
        defer_minutes=minutes,
        outcome="user_discussed_observation",
        summary="User opened Discuss on the proactive suggestion.",
        workspace=workspace,
    )


def defer_linked_drive_after_kanban_approve(
    drive_id: str,
    *,
    proposed: str = "",
    workspace: str | None = None,
) -> tuple[bool, str]:
    """Backoff a linked drive while kanban-backed approved work runs."""
    if not drive_id:
        return False, "no drive_id"
    from drive_engine import defer_drive

    minutes = _drives_cfg_int("approved_kanban_defer_minutes", 10_080)
    summary = f"User approved kanban work: {(proposed or 'carry out approved work')[:200]}"
    return defer_drive(
        drive_id,
        defer_minutes=minutes,
        outcome="approved_kanban",
        summary=summary,
        workspace=workspace,
    )


def reconcile_linked_drive_on_observation_event(
    drive_id: str,
    *,
    event: str,
    summary: str = "",
    task_id: str = "",
    run_id: str = "",
    workspace: str | None = None,
) -> tuple[bool, str]:
    """Shared terminal-event handler for observation-linked drives."""
    if not drive_id:
        return False, "no drive_id"
    if event == "completed":
        from drive_engine import resolve_drive

        return resolve_drive(
            drive_id,
            resolution_summary=f"Kanban task completed: {summary}"[:500],
            trigger="initiative",
            evidence={
                "validation": "kanban_completed",
                "task_id": task_id,
                "run_id": run_id or "",
            },
            workspace=workspace,
        )
    from drive_engine import defer_drive

    outcome = {
        "gave_up": "kanban_gave_up",
        "cancelled": "kanban_cancelled",
    }.get(event, "kanban_terminal")
    verb = {
        "gave_up": "gave up",
        "cancelled": "was cancelled",
    }.get(event, "ended")
    minutes = _drives_cfg_int(
        "observation_kanban_failure_defer_minutes",
        120 if event == "gave_up" else 240,
    )
    return defer_drive(
        drive_id,
        defer_minutes=minutes,
        outcome=outcome,
        summary=f"Kanban task {verb}: {summary}"[:500],
        workspace=workspace,
    )
