"""Tool wrappers for drive engine operations."""
from __future__ import annotations

import json

from langchain_core.tools import tool

from tools._logging import _debug_log, _emit_input_status


@tool
def list_drives(limit: int = 10) -> str:
    """List active drives sorted by urgency. Each drive has a short 'ref' number (1, 2, 3...) for use with resolve_drive and dismiss_drive."""
    _debug_log("[TOOL] list_drives called", "TOOL")
    _emit_input_status("Reading drives…")
    try:
        from drive_engine import get_active_drives

        drives = get_active_drives(limit=max(1, min(int(limit), 20)))
        if not drives:
            return "No active drives."
        return json.dumps({"active_drives": drives}, indent=2, ensure_ascii=True)
    finally:
        _emit_input_status("")


@tool
def resolve_drive(
    drive_id: str,
    resolution_summary: str,
    trigger: str = "manual",
    evidence: str = "",
) -> str:
    """Resolve an active drive. Use the numeric ref from list_drives as the drive_id (e.g. '1', '2'). Optional trigger: manual|initiative."""
    _debug_log("[TOOL] resolve_drive called", "TOOL")
    _emit_input_status("Resolving drive…")
    try:
        from drive_engine import resolve_drive as _resolve_drive
        from drive_engine import DRIVE_ACTION_THREAD_PREFIX
        from persistence import get_current_agent_thread_id

        clean_trigger = str(trigger or "manual").strip().lower() or "manual"
        thread_id = str(get_current_agent_thread_id() or "").strip()
        if clean_trigger == "manual" and thread_id.startswith(DRIVE_ACTION_THREAD_PREFIX):
            clean_trigger = "initiative"
        if clean_trigger not in {"manual", "initiative", "tool", "auto"}:
            clean_trigger = "manual"

        parsed_evidence = None
        if isinstance(evidence, str) and evidence.strip():
            try:
                obj = json.loads(evidence)
                if isinstance(obj, dict):
                    parsed_evidence = obj
            except Exception:
                parsed_evidence = None

        ok, msg = _resolve_drive(
            drive_id=drive_id,
            resolution_summary=resolution_summary,
            trigger=clean_trigger,
            evidence=parsed_evidence,
        )
        return msg if ok else f"Error: {msg}"
    finally:
        _emit_input_status("")


@tool
def dismiss_drive(drive_id: str, reason: str) -> str:
    """Dismiss an active drive that is no longer relevant. Use the numeric ref from list_drives as the drive_id (e.g. '1', '2')."""
    _debug_log("[TOOL] dismiss_drive called", "TOOL")
    _emit_input_status("Dismissing drive…")
    try:
        from drive_engine import dismiss_drive as _dismiss_drive

        ok, msg = _dismiss_drive(drive_id=drive_id, reason=reason)
        return msg if ok else f"Error: {msg}"
    finally:
        _emit_input_status("")


@tool
def create_drive(description: str, drive_type: str = "exploration", suggested_action: str = "") -> str:
    """Create a new drive to follow up later."""
    _debug_log("[TOOL] create_drive called", "TOOL")
    _emit_input_status("Creating drive…")
    try:
        from drive_engine import create_drive as _create_drive

        ok, msg = _create_drive(
            description=description,
            drive_type=drive_type,
            suggested_action=suggested_action,
        )
        return msg if ok else f"Error: {msg}"
    finally:
        _emit_input_status("")
