"""file_tools.py - read-only file operace pro AI. Bezpečné cesty."""
from __future__ import annotations

from pathlib import Path
from typing import Any

PROJECT_ROOT = Path("/home/oem/CyberBrain26-lab").resolve()
MAX_READ = 50_000


def _safe_path(raw: str) -> Path:
    p = Path(raw).expanduser()
    if not p.is_absolute():
        p = PROJECT_ROOT / p
    p = p.resolve()
    try:
        p.relative_to(PROJECT_ROOT)
    except ValueError:
        raise PermissionError(f"Mimo projekt: {p}")
    return p


def read_file(path: str, max_bytes: int = MAX_READ) -> dict[str, Any]:
    try:
        p = _safe_path(path)
        if not p.is_file():
            return {"status": "error", "error": f"neni soubor: {path}"}
        data = p.read_text(encoding="utf-8", errors="replace")
        trunc = len(data.encode("utf-8")) > max_bytes
        if trunc:
            data = data[:max_bytes]
        return {"status": "success", "path": str(p.relative_to(PROJECT_ROOT)),
                "truncated": trunc, "content": data}
    except Exception as e:
        return {"status": "error", "error": f"{type(e).__name__}: {e}"}


def list_dir(path: str = ".") -> dict[str, Any]:
    try:
        p = _safe_path(path)
        if not p.is_dir():
            return {"status": "error", "error": f"neni adresar: {path}"}
        entries = []
        for item in sorted(p.iterdir()):
            try:
                st = item.stat()
                entries.append({
                    "name": item.name,
                    "type": "dir" if item.is_dir() else "file",
                    "size": st.st_size,
                })
            except Exception:
                entries.append({"name": item.name, "type": "?"})
            if len(entries) >= 200:
                break
        return {"status": "success",
                "path": str(p.relative_to(PROJECT_ROOT)),
                "entries": entries}
    except Exception as e:
        return {"status": "error", "error": f"{type(e).__name__}: {e}"}


def find_files(pattern: str, path: str = ".", max_results: int = 50) -> dict[str, Any]:
    try:
        base = _safe_path(path)
        matches = []
        for f in base.rglob("*"):
            if not f.is_file():
                continue
            if f.name.startswith(".") and not pattern.startswith("."):
                continue
            parts = set(f.parts)
            if parts & {"venv", "__pycache__", ".git", "node_modules", "_legacy"}:
                continue
            if pattern.lower() in f.name.lower():
                matches.append(str(f.relative_to(PROJECT_ROOT)))
                if len(matches) >= max_results:
                    break
        return {"status": "success", "pattern": pattern,
                "count": len(matches), "matches": matches}
    except Exception as e:
        return {"status": "error", "error": f"{type(e).__name__}: {e}"}


READ_FILE_TOOL = {"type": "function", "function": {
    "name": "read_file",
    "description": "Precte obsah souboru v projektu (read-only).",
    "parameters": {"type": "object",
        "properties": {
            "path": {"type": "string", "description": "Relativni cesta k souboru"},
            "max_bytes": {"type": "integer", "minimum": 100, "maximum": 200000},
        },
        "required": ["path"], "additionalProperties": False}}}

LIST_DIR_TOOL = {"type": "function", "function": {
    "name": "list_dir",
    "description": "Vypise obsah adresare v projektu.",
    "parameters": {"type": "object",
        "properties": {"path": {"type": "string", "description": "Relativni cesta (vychozi .)"}},
        "required": [], "additionalProperties": False}}}

FIND_FILES_TOOL = {"type": "function", "function": {
    "name": "find_files",
    "description": "Najde soubory podle casti nazvu (rekurzivne, bez venv/.git).",
    "parameters": {"type": "object",
        "properties": {
            "pattern": {"type": "string"},
            "path": {"type": "string", "description": "Kde hledat (vychozi .)"},
            "max_results": {"type": "integer", "minimum": 1, "maximum": 200},
        },
        "required": ["pattern"], "additionalProperties": False}}}

__all__ = [
    "FIND_FILES_TOOL",
    "LIST_DIR_TOOL",
    "READ_FILE_TOOL",
    "find_files",
    "list_dir",
    "read_file",
]
