"""submit_feedback -- Report bugs or request features.

Posts to the same Google Sheet webhook as telemetry but with
event="feedback", so the Apps Script routes it to a dedicated
Feedback tab — clean and separate from telemetry logs.
"""

import logging
from datetime import datetime, timezone
from typing import Any

from ..utils.telemetry import _post_event, _session

logger = logging.getLogger(__name__)

TOOL_DEFINITION = {
    "name": "submit_feedback",
    "description": (
        "Submit a bug report or feature request. Use when the user wants "
        "to report an issue they hit or suggest a new capability. The "
        "feedback is sent to the team automatically."
    ),
    "inputSchema": {
        "type": "object",
        "properties": {
            "type": {
                "type": "string",
                "enum": ["bug", "feature_request"],
                "description": "The kind of feedback: 'bug' or 'feature_request'.",
            },
            "title": {
                "type": "string",
                "description": "Short one-line summary of the bug or feature request.",
            },
            "description": {
                "type": "string",
                "description": (
                    "Detailed description. For bugs: what happened, what was "
                    "expected, and steps to reproduce. For features: what the "
                    "user wants and why."
                ),
            },
        },
        "required": ["type", "title", "description"],
    },
}


async def run(arguments: dict[str, Any]) -> str:
    feedback_type = arguments.get("type", "")
    title = arguments.get("title", "").strip()
    description = arguments.get("description", "").strip()

    if feedback_type not in ("bug", "feature_request"):
        return "STATUS: ERROR\n\ntype must be 'bug' or 'feature_request'."
    if not title:
        return "STATUS: ERROR\n\ntitle is required."
    if not description:
        return "STATUS: ERROR\n\ndescription is required."

    _post_event({
        "event": "feedback",
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "feedback_type": feedback_type,
        "title": title,
        "description": description,
        "user": _session.get("user", "unknown"),
        "hostname": _session.get("hostname", "unknown"),
        "server_version": _session.get("server_version", "unknown"),
    })

    label = "Bug report" if feedback_type == "bug" else "Feature request"
    return (
        f"STATUS: SUBMITTED\n\n"
        f"{label} submitted: \"{title}\"\n\n"
        f"The feedback has been sent to the team. Thank the user and "
        f"let them know it's been received."
    )
