#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Worker tool: task submission, salience scoring, and capture signing.

Split from worker_tools.py for Law 7 compliance.
"""
from __future__ import annotations

_SALIENCE_SCORES = {
    "reasoning": 1.5, "tool_call": 1.0, "tool_result": 0.8,
    "brain_query": 2.0, "complete": 3.0, "task_start": 1.0,
}


def tool_submit_task(title: str, domain: str = "general",
                     complexity: str = "medium", description: str = "") -> str:
    try:
        from pulse.tasks.pulse_relay import parse_manual_tasks
        from pulse.tasks.pulse_dispatcher import TaskDispatcher
        task_spec = f"{title}:{domain}:{complexity}"
        tasks = parse_manual_tasks([task_spec])
        if description:
            tasks[0]["description"] = description
        dispatcher = TaskDispatcher(verbose=False)
        if not dispatcher._hmac_key:
            return "ERROR: No HMAC key — cannot dispatch tasks"
        dispatcher.dispatch(tasks, prompt=title)
        return f"OK: Task '{title}' posted to board (domain={domain}, complexity={complexity})"
    except Exception as e:
        return f"ERROR posting task: {e}"


def compute_salience(event_type: str, tool_name: str = "", error: bool = False) -> float:
    """Score event salience 0.1-10.0 for knowledge extraction priority."""
    if error:
        return 4.0
    base = _SALIENCE_SCORES.get(event_type, 0.5)
    if tool_name in ("write_file", "edit_file"):
        base *= 2.0
    elif tool_name == "run_command":
        base *= 1.5
    return min(base, 10.0)


def _worker_sign(content_part: str, worker_id: str) -> str:
    """Sign a capture line using the same HMAC format as agent daemons."""
    try:
        from pulse.core.pulse_crypto import PulseCrypto
        crypto = PulseCrypto()
        sig = crypto.sign_string(content_part, worker_id)
        return f"{content_part} | SIG: {sig}"
    except Exception as e:
        from pulse.core.paths import _is_dev_mode
        if _is_dev_mode():
            import logging
            logging.getLogger("pulse.workers").warning(
                "Worker signing failed (dev mode — unsigned): %s", e)
            return content_part
        raise RuntimeError(
            f"Worker signing failed for {worker_id}: {e}. "
            "Unsigned capture lines are not allowed in production mode."
        )
