import os
import re
import yaml
import sys

def slugify(text):
    # Заменяем всё, кроме букв (включая кириллицу), цифр и дефиса — на дефис
    text = re.sub(r'[^а-яА-Яa-zA-Z0-9\-]+', '-', text)
    text = re.sub(r'-{2,}', '-', text)
    text = text.strip('-')
    return text.lower()

def process_md_file(filepath, base_dir):
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()
    except Exception as e:
        print(f"⚠️ Ошибка чтения {filepath}: {e}")
        return

    match = re.match(r'^---\n(.*?)\n---\n(.*)', content, re.DOTALL)
    if not match:
        print(f"ℹ️ Создаётся frontmatter для {filepath}")
        frontmatter = {}
        body = content
    else:
        frontmatter_raw, body = match.groups()
        frontmatter = yaml.safe_load(frontmatter_raw) or {}

    title = frontmatter.get('title')
    filename = os.path.splitext(os.path.basename(filepath))[0]

    if not title:
        title = filename
        frontmatter['title'] = title
        print(f"ℹ️  Добавлен title из имени файла: {title} в {filepath}")

    rel_dir = os.path.relpath(os.path.dirname(filepath), base_dir)
    slug_parts = []

    if rel_dir != '.':
        slug_parts.append(slugify(rel_dir.replace('\\', '/')))

    slug_parts.append(slugify(title))
    new_slug = '/'.join(slug_parts)

    current_slug = frontmatter.get('slug', '')
    if current_slug == new_slug:
        print(f"✅ {filepath} (slug уже установлен)")
        return
    if re.match(r'^[a-z0-9\-/]+$', current_slug):
        print(f"♻️  Обновление латинского slug → {new_slug} в {filepath}")
    else:
        print(f"✍️  Установка slug → {new_slug} в {filepath}")

    frontmatter['slug'] = new_slug
    new_frontmatter_raw = yaml.dump(frontmatter, allow_unicode=True, sort_keys=False).strip()
    new_content = f'---\n{new_frontmatter_raw}\n---\n{body}'

    try:
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(new_content)
    except Exception as e:
        print(f"❌ Ошибка записи {filepath}: {e}")

def walk_md_files(base_dir):
    for root, dirs, files in os.walk(base_dir):
        for file in files:
            if (file.endswith('.md') or file.endswith('.mdx')) and not file.lower().startswith('index.'):
                process_md_file(os.path.join(root, file), base_dir)
    print("\nГотово!")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Использование: python add_slug.py <путь_к_папке_с_документацией>")
        sys.exit(1)

    folder_path = sys.argv[1]
    if not os.path.isdir(folder_path):
        print("❌ Указан неверный путь к папке.")
        sys.exit(1)

    walk_md_files(folder_path)