"""Submit SOP feedback tool — discovered by FileSystemProvider."""

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

from fastmcp.tools import tool
from pydantic import Field

from src.utils import SOP
from src.utils.storage import LocalFilesystemBackend

logger = logging.getLogger(__name__)


backend = LocalFilesystemBackend.from_env()


EPHEMERAL_WARNING = (
    "⚠️ WARNING: This data was written to ephemeral storage and may be lost "
    "when the package cache is refreshed. Set the SOP_STORAGE_DIR environment "
    "variable to a persistent path to avoid data loss."
)


@tool()
def submit_sop_feedback(
    sop_name: Annotated[str, Field(description="Name of the SOP.")],
    feedback: Annotated[str, Field(min_length=1, description="The improvement suggestion or feedback text.")],
) -> dict[str, Any]:
    """Submit improvement feedback for a specific SOP.

    Collects user feedback about an SOP and stores it in a feedback.md file
    inside the SOP's folder. This feedback will be used to optimize the SOP
    in its next revision.
    """
    logger.info("Invoking submit_sop_feedback with args: sop_name=%s, feedback=<%s chars>", sop_name, len(feedback))

    if not backend.sop_exists(sop_name):
        raise ValueError(f"SOP '{sop_name}' not found. Available: {', '.join(backend.list_sops())}")

    content = backend.read_sop(sop_name)
    sop = SOP.from_content(content)

    timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
    entry = f"## Feedback — {timestamp}\n\n**SOP Version:** v{sop.version}\n\n{feedback}\n\n---\n\n"

    try:
        backend.append_feedback(sop_name, entry)
    except OSError as e:
        logger.warning("Failed to write feedback for %s: %s", sop_name, e)
        return {"error": f"Failed to write feedback file: {e}"}

    logger.info("Feedback submitted for %s v%s at %s", sop_name, sop.version, timestamp)
    result: dict[str, Any] = {
        "success": True,
        "sop_name": sop_name,
        "sop_version": sop.version,
        "timestamp": timestamp,
        "message": f"Feedback recorded for '{sop_name}' (v{sop.version}). It will be considered in the next revision.",
    }
    if backend.is_ephemeral:
        result["warning"] = EPHEMERAL_WARNING
    return result
