"""save_report -- Write a markdown or text report to the workspace.

Generic utility tool for persisting AI-generated analysis, insights,
and discussion notes to a file. Works across any MCP client (Cursor,
Claude Desktop, etc.) and any OS.
"""

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

from ..utils import state

logger = logging.getLogger(__name__)

TOOL_DEFINITION = {
    "name": "save_report",
    "description": (
        "Save a markdown or text report to the workspace. Use this to "
        "persist portfolio insights, customer analysis, discussion notes, "
        "or any findings the user wants to share. The AI generates the "
        "content; this tool writes it to a file. "
        "Example filenames: 'portfolio/insights-2026-03-14.md', "
        "'customers/nbn-co-ltd/analysis.md'."
    ),
    "inputSchema": {
        "type": "object",
        "properties": {
            "filename": {
                "type": "string",
                "description": (
                    "Relative path for the report file. Directories are "
                    "created automatically. Examples: "
                    "'portfolio/insights-2026-03-14.md', "
                    "'customers/nbn-co-ltd/analysis.md'."
                ),
            },
            "content": {
                "type": "string",
                "description": "The full markdown or text content to write.",
            },
            "working_directory": {
                "type": "string",
                "description": "Workspace directory. The AI passes this automatically.",
            },
        },
        "required": ["filename", "content"],
    },
}


async def run(arguments: dict[str, Any]) -> str:
    """Execute the save_report tool."""
    state.set_working_dir(arguments.get("working_directory"))
    working_dir = state.get_working_dir()

    filename = arguments.get("filename", "")
    content = arguments.get("content", "")

    if not filename:
        return "STATUS: ERROR\n\nfilename is required."
    if not content:
        return "STATUS: ERROR\n\ncontent is required."

    if ".." in filename or filename.startswith("/"):
        return (
            "STATUS: ERROR\n\n"
            "filename must be a relative path within the workspace. "
            "No '..' or absolute paths allowed."
        )

    out_path = working_dir / filename
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(content, encoding="utf-8")

    size_kb = out_path.stat().st_size / 1024

    return (
        f"STATUS: SAVED\n\n"
        f"Report written to `{out_path}` ({size_kb:.1f} KB).\n"
        f"Tell the user the report has been saved and where to find it."
    )
