from __future__ import annotations

from langchain_core.tools import tool

from tools._logging import _debug_log, _emit_input_status
from utils.delegation_blackboard import (
    append_markdown_block,
    get_limits,
    read_blackboard_excerpt,
    resolve_delegation_scratch_path,
)


@tool
def append_delegation_scratch(
    content: str,
    section: str = "",
    parent_thread_id: str = "",
    delegation_job_id: str = "",
) -> str:
    """Append content to delegation scratch file memory/delegation/<parent>/<job>.md. parent_thread_id and delegation_job_id are optional when delegation context is already set by delegate_task."""
    _debug_log("[TOOL] append_delegation_scratch called", "TOOL")
    _emit_input_status("Appending delegation scratch…")
    body = (content or "").strip()
    if not body:
        _emit_input_status("")
        return "No content provided. Nothing appended."

    abs_path, safe_parent, safe_job, err = resolve_delegation_scratch_path(
        parent_thread_id, delegation_job_id, allow_write=True
    )
    if err:
        _emit_input_status("")
        return err

    max_append_chars, max_file_bytes = get_limits()
    if len(body) > max_append_chars:
        body = body[:max_append_chars] + "\n\n[Truncated at delegation_scratch_max_append_chars.]"

    ok, err_msg = append_markdown_block(
        abs_path=abs_path or "",
        safe_parent=safe_parent,
        safe_job=safe_job,
        section=section,
        body=body,
        max_file_bytes=max_file_bytes,
    )
    if not ok:
        _emit_input_status("")
        return err_msg

    _emit_input_status("")
    return f"Delegation scratch updated at {abs_path}"


@tool
def read_delegation_scratch(
    max_chars: int = 4000,
    parent_thread_id: str = "",
    delegation_job_id: str = "",
) -> str:
    """Read delegation scratch for memory/delegation/<parent>/<job>.md. parent_thread_id and delegation_job_id are optional when delegation context is already set by delegate_task."""
    _debug_log("[TOOL] read_delegation_scratch called", "TOOL")
    _emit_input_status("Reading delegation scratch…")
    abs_path, _safe_parent, safe_job, err = resolve_delegation_scratch_path(
        parent_thread_id, delegation_job_id, allow_write=False
    )
    if err:
        _emit_input_status("")
        return err
    if not abs_path:
        _emit_input_status("")
        return f"Delegation scratch not found for job '{safe_job}'."
    text = read_blackboard_excerpt(abs_path, max_chars=max_chars)
    if not text:
        _emit_input_status("")
        return f"Delegation scratch not found for job '{safe_job}'."
    _emit_input_status("")
    return text

