"""Legacy compatibility facade for tool and mail helpers."""

from pathlib import Path

from backend import mail_read_runtime as _mail_read_runtime
from backend.config import WORKSPACE_ROOT
from backend.gmail_helpers_runtime import _gmail_message_headers
from backend.mail_helpers_runtime import _outlook_select_mailboxes
from backend.mail_read_runtime import _gmail_build_date_query_parts
from backend.tool_dispatch_runtime import _execute_tool, _slack_post_message


OUTLOOK_SUPPORT = _mail_read_runtime.OUTLOOK_SUPPORT
_outlook_session = _mail_read_runtime._outlook_session
_outlook_build_mail_restriction = _mail_read_runtime._outlook_build_mail_restriction

_ALLOWED_ATTACHMENT_DIRS = ("output", "attachments", "downloads")


def _resolve_attachment_path(raw: str) -> Path | None:
	if not raw:
		return None
	path = Path(raw)
	if not path.is_absolute():
		path = WORKSPACE_ROOT / path
	try:
		path = path.resolve()
	except Exception:
		return None
	if not path.is_file():
		return None
	for allowed in _ALLOWED_ATTACHMENT_DIRS:
		allowed_dir = (WORKSPACE_ROOT / allowed).resolve()
		try:
			path.relative_to(allowed_dir)
			return path
		except ValueError:
			continue
	return None


def _outlook_get_inbox(
	count: int = 250,
	unread_only: bool = False,
	folder: str = "Inbox",
	mailbox: str = "ALL",
	today_only: bool = False,
	since: str = "",
	until: str = "",
	body_length: int = 300,
) -> str:
	original_support = _mail_read_runtime.OUTLOOK_SUPPORT
	original_session = _mail_read_runtime._outlook_session
	original_restriction = _mail_read_runtime._outlook_build_mail_restriction
	try:
		_mail_read_runtime.OUTLOOK_SUPPORT = OUTLOOK_SUPPORT
		_mail_read_runtime._outlook_session = _outlook_session
		_mail_read_runtime._outlook_build_mail_restriction = _outlook_build_mail_restriction
		return _mail_read_runtime._outlook_get_inbox(
			count=count,
			unread_only=unread_only,
			folder=folder,
			mailbox=mailbox,
			today_only=today_only,
			since=since,
			until=until,
			body_length=body_length,
		)
	finally:
		_mail_read_runtime.OUTLOOK_SUPPORT = original_support
		_mail_read_runtime._outlook_session = original_session
		_mail_read_runtime._outlook_build_mail_restriction = original_restriction

