"""PostToolUse hook: link task_id to session after next_task returns.

Matcher: mcp__peon-mcp__next_task

Reads the tool_response from stdin (the task dict returned by next_task),
extracts the task id, and calls PUT /api/sessions/{session_id} to link them.
Always exits 0 — session linking is observability, not critical path.
"""

import json
import os
import sys

from peon_mcp.hooks.common import api_request


def main() -> None:
    session_id = os.environ.get("PEON_SESSION_ID", "")
    if not session_id:
        sys.exit(0)

    # Read the hook event from stdin
    try:
        event = json.loads(sys.stdin.read())
    except (json.JSONDecodeError, OSError):
        sys.exit(0)

    tool_response = event.get("tool_response", "")

    # tool_response is a string — could be JSON (the task dict) or a plain
    # string like "no tasks available".
    task_id = None
    if isinstance(tool_response, str):
        try:
            parsed = json.loads(tool_response)
            if isinstance(parsed, dict):
                task_id = parsed.get("id")
        except (json.JSONDecodeError, ValueError):
            pass
    elif isinstance(tool_response, dict):
        task_id = tool_response.get("id")

    if task_id is None:
        sys.exit(0)

    api_request("PUT", f"/api/sessions/{session_id}", {"task_id": int(task_id)})
    sys.exit(0)


if __name__ == "__main__":
    main()
