from __future__ import annotations

import re
import textwrap
from pathlib import Path


def slugify(text: str, max_len: int = 48) -> str:
    text = text.lower().strip()
    text = re.sub(r"[àáâãäå]", "a", text)
    text = re.sub(r"[èéêë]", "e", text)
    text = re.sub(r"[ìíîï]", "i", text)
    text = re.sub(r"[òóôõö]", "o", text)
    text = re.sub(r"[ùúûü]", "u", text)
    text = re.sub(r"[^a-z0-9]+", "-", text)
    text = re.sub(r"-+", "-", text).strip("-")
    return (text or "item")[:max_len]


def wrap_text(text: str, width: int) -> list[str]:
    return textwrap.wrap(text.replace("\n", " ").strip(), width=width) or [""]


def read_text_files(folder: Path, limit_chars: int = 40_000) -> str:
    if not folder.exists():
        return ""
    chunks: list[str] = []
    total = 0
    for path in sorted(folder.rglob("*")):
        if not path.is_file():
            continue
        if path.suffix.lower() not in {".md", ".txt", ".markdown"}:
            continue
        try:
            body = path.read_text(encoding="utf-8", errors="ignore").strip()
        except OSError:
            continue
        if not body:
            continue
        piece = f"### FILE: {path.name}\n{body}\n"
        if total + len(piece) > limit_chars:
            remain = limit_chars - total
            if remain > 200:
                chunks.append(piece[:remain] + "\n...[truncated]")
            break
        chunks.append(piece)
        total += len(piece)
    return "\n".join(chunks)


def hex_to_rgb(color: str) -> tuple[int, int, int]:
    c = color.lstrip("#")
    if len(c) == 3:
        c = "".join(ch * 2 for ch in c)
    return int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16)
