"""Shared path normalization and internal guard-message detection."""

from __future__ import annotations

import hashlib
import os
import re
import sys

_INTERNAL_GUARD_MARKERS: tuple[str, ...] = (
    "recorded, not authoritative",
    "could not parse your tool_call",
    "return exactly one executable tool call",
    "missing required arguments",
    "is missing required arguments",
    "─── current task plan",
    "─── open steps",
    "[internal / format only]",
    "your previous tool call was invalid",
    "[kanban / recorded, not authoritative]",
    "kanban completion repair",
    "every tool call in the last round failed",
    "before writing prose, repair",
)


def is_internal_guard_user_text(text: str) -> bool:
    """True for loop nudges, recovery prompts, malformed-tool repair, task-plan blocks."""
    if not isinstance(text, str):
        return False
    s = text.strip()
    if not s:
        return False
    lower = s.lower()
    return any(marker in lower for marker in _INTERNAL_GUARD_MARKERS)


def _normcase_path(path: str) -> str:
    p = os.path.normpath(path)
    if sys.platform == "darwin":
        return p.lower()
    return p


def normalize_path_bucket(raw: str, *, workspace: str) -> str:
    """Expand ~, resolve relative to workspace, normcase on darwin; stable bucket string."""
    stripped = (raw or "").strip().strip(' "\n,')
    if not stripped:
        return ""

    try:
        from utils.path_safety import safe_resolve_path

        ws = (workspace or "").strip() or os.path.expanduser("~/.mugi/workspace")
        resolved, err = safe_resolve_path(ws, stripped, allow_write=False, create_parents=False)
        if resolved and not err:
            try:
                real = os.path.realpath(resolved)
            except OSError:
                real = resolved
            return _normcase_path(os.path.normpath(real))
    except Exception:
        pass

    try:
        expanded = os.path.expanduser(stripped)
        if expanded:
            abs_path = os.path.abspath(expanded)
            return _normcase_path(os.path.normpath(abs_path))
    except Exception:
        pass

    digest = hashlib.sha256(stripped.encode("utf-8", errors="replace")).hexdigest()[:12]
    return f"raw:{digest}"


def truncate_path_display(path_bucket: str, *, max_len: int = 80) -> str:
    """Truncate a path bucket for user-visible nudges."""
    if not path_bucket:
        return ""
    if len(path_bucket) <= max_len:
        return path_bucket
    head = max_len // 2 - 1
    tail = max_len - head - 1
    return f"{path_bucket[:head]}…{path_bucket[-tail:]}"


def fuzzy_slug_normalize(name: str) -> str:
    """Normalize basename for fuzzy sibling matching (hyphen/underscore insensitive)."""
    base = os.path.basename(name or "")
    return re.sub(r"[-_]+", "", base.lower())
