"""Safe local file-generation tools for user-facing deliverables."""

from __future__ import annotations

import os
import re
import zipfile
from datetime import datetime, timezone
from pathlib import Path

from langchain_core.tools import tool

from app.tools._docx import build_docx_package

_MAX_CONTENT_CHARS = 100_000


def _output_root() -> Path:
    configured = (os.environ.get("MOFIX_OUTPUT_DIR") or "").strip()
    if configured:
        root = Path(configured).expanduser().resolve()
    elif Path("/data").is_dir():
        root = Path("/data/mofix-output")
    else:
        root = Path.cwd() / "outputs"
    root.mkdir(parents=True, exist_ok=True)
    return root


def _safe_docx_name(filename: str, title: str) -> str:
    requested = Path((filename or "").strip()).name
    stem = Path(requested).stem if requested else title.strip()
    stem = re.sub(r"[^\w.-]+", "-", stem, flags=re.UNICODE).strip(".-_")
    if not stem:
        stem = "document"
    return f"{stem[:80]}.docx"


def _write_docx(path: Path, title: str, content: str) -> None:
    """标题作为一级标题段落并入 Markdown 正文,统一走共享 .docx 打包。"""
    package, _ = build_docx_package(f"# {title}\n{content}")
    path.write_bytes(package)


@tool
def generate_word_document(title: str, content: str, filename: str = "") -> str:
    """Generate a real ``.docx`` Word document and return its verifiable local path.

    Use this tool whenever the user asks for a Word document, Word template, or
    ``.docx`` file. ``content`` may use simple Markdown headings and bullet lists.
    ``filename`` is optional and must be a file name rather than an arbitrary path.
    """
    clean_title = (title or "").strip()
    clean_content = (content or "").strip()
    if not clean_title:
        return "[word] 生成失败:title 不能为空。"
    if not clean_content:
        return "[word] 生成失败:content 不能为空。"
    if len(clean_content) > _MAX_CONTENT_CHARS:
        return f"[word] 生成失败:content 超过 {_MAX_CONTENT_CHARS} 字符上限。"

    output_path = _output_root() / _safe_docx_name(filename, clean_title)
    try:
        _write_docx(output_path, clean_title, clean_content)
    except (OSError, ValueError, zipfile.BadZipFile) as exc:
        return f"[word] 生成失败:{type(exc).__name__}: {exc}"

    generated_at = datetime.now(timezone.utc).isoformat()
    return (
        "Word 文档已生成。\n"
        f"文件路径:{output_path}\n"
        f"文件大小:{output_path.stat().st_size} bytes\n"
        f"生成时间:{generated_at}"
    )


def get_tools() -> list:
    return [generate_word_document]