"""Documentation API - serves client documentation pages."""
import os
import markdown
from markupsafe import escape
from flask import Blueprint, jsonify
from flask_login import login_required
from src.utils import sanitize_html

docs_bp = Blueprint('docs', __name__)

# Path to client documentation files
DOCS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'client_docs')

# Singleton Markdown instance (performance: avoid reinitializing extensions on every call)
_docs_md = markdown.Markdown(
    extensions=[
        'tables',
        'fenced_code',
        'toc',
        'admonition',
        'attr_list',
        'md_in_html',
        'sane_lists'
    ],
    extension_configs={
        'toc': {'permalink': False, 'toc_depth': 3}
    }
)


def _read_doc_file(filepath):
    """Read and cache a documentation file. Returns content string."""
    mtime = os.path.getmtime(filepath)
    cache = getattr(_read_doc_file, '_cache', {})
    cached = cache.get(filepath)
    if cached and cached[0] == mtime:
        return cached[1]
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()
    cache[filepath] = (mtime, content)
    _read_doc_file._cache = cache
    return content


def get_nav_structure(is_admin=False):
    """Return navigation structure for documentation."""
    sections = [
        {
            "title": "Guide Utilisateur",
            "icon": "fa-book-open",
            "slug": "guide-utilisateur",
            "pages": [
                {"title": "Vue d'ensemble", "slug": "index"},
                {"title": "Premiers pas", "slug": "premiers-pas"},
                {"title": "Enregistrement", "slug": "enregistrement"},
                {"title": "Transcriptions", "slug": "transcriptions"},
                {"title": "Recherche IA", "slug": "recherche-ia"},
                {"title": "Partage", "slug": "partage"},
                {"title": "Dossiers", "slug": "dossiers"},
                {"title": "Groupes", "slug": "groupes"},
                {"title": "Paramètres", "slug": "parametres"},
                {"title": "Application mobile", "slug": "application-mobile"}
            ]
        },
        {
            "title": "Dépannage",
            "icon": "fa-life-ring",
            "slug": "depannage",
            "pages": [
                {"title": "Vue d'ensemble", "slug": "index"},
                {"title": "Transcription", "slug": "transcription"},
                {"title": "Performance", "slug": "performance"},
                {"title": "Fonctionnalités", "slug": "fonctionnalites"}
            ]
        }
    ]

    if is_admin:
        sections.insert(1, {
            "title": "Guide Administrateur",
            "icon": "fa-shield-alt",
            "slug": "guide-admin",
            "pages": [
                {"title": "Vue d'ensemble", "slug": "index"},
                {"title": "Gestion des utilisateurs", "slug": "gestion-utilisateurs"},
                {"title": "Gestion des groupes", "slug": "gestion-groupes"},
                {"title": "Statistiques", "slug": "statistiques"},
                {"title": "Paramètres système", "slug": "parametres-systeme"},
                {"title": "Modèles IA", "slug": "modeles-ia"},
                {"title": "Prompts", "slug": "prompts"},
                {"title": "Recherche sémantique", "slug": "recherche-semantique"},
                {"title": "Rétention", "slug": "retention"},
                {"title": "SSO", "slug": "sso"}
            ]
        })

    return sections


def render_markdown_content(md_text):
    """Render markdown to sanitized HTML with extensions for admonitions, tables, etc."""
    _docs_md.reset()
    html = _docs_md.convert(md_text)
    toc_html = getattr(_docs_md, 'toc', '')
    # Sanitize rendered HTML to prevent XSS
    html = sanitize_html(html)
    return html, toc_html


@docs_bp.route('/api/docs/nav')
@login_required
def docs_nav():
    """Return navigation structure based on user role."""
    from flask_login import current_user
    is_admin = getattr(current_user, 'is_admin', False)
    sections = get_nav_structure(is_admin)
    return jsonify({"sections": sections})


@docs_bp.route('/api/docs/page/<section>/<page>')
@login_required
def docs_page(section, page):
    """Return rendered HTML for a documentation page."""
    # Sanitize path components to prevent directory traversal
    safe_section = os.path.basename(section)
    safe_page = os.path.basename(page)

    allowed_sections = ['guide-utilisateur', 'guide-admin', 'depannage']
    if safe_section not in allowed_sections:
        return jsonify({"error": "Section invalide"}), 404

    # Admin guide requires admin role
    if safe_section == 'guide-admin':
        from flask_login import current_user
        if not getattr(current_user, 'is_admin', False):
            return jsonify({"error": "Accès refusé"}), 403

    filepath = os.path.join(DOCS_DIR, safe_section, f"{safe_page}.md")

    if not os.path.isfile(filepath):
        return jsonify({"error": "Page non trouvée"}), 404

    content = _read_doc_file(filepath)
    html, toc = render_markdown_content(content)

    return jsonify({
        "html": html,
        "toc": toc,
        "section": safe_section,
        "page": safe_page
    })


@docs_bp.route('/api/docs/search')
@login_required
def docs_search():
    """Simple text search across all documentation pages."""
    from flask import request
    from flask_login import current_user

    query = request.args.get('q', '').strip().lower()
    if not query or len(query) < 2:
        return jsonify({"results": []})

    is_admin = getattr(current_user, 'is_admin', False)
    results = []

    sections = get_nav_structure(is_admin)

    for section in sections:
        section_dir = os.path.join(DOCS_DIR, section['slug'])
        if not os.path.isdir(section_dir):
            continue

        for page_info in section['pages']:
            filepath = os.path.join(section_dir, f"{page_info['slug']}.md")
            if not os.path.isfile(filepath):
                continue

            content = _read_doc_file(filepath)

            content_lower = content.lower()
            if query in content_lower:
                # Find matching line for context
                lines = content.split('\n')
                snippet = ''
                for line in lines:
                    if query in line.lower():
                        # HTML-escape snippet to prevent XSS
                        snippet = str(escape(line.strip()[:150]))
                        break

                results.append({
                    "section": section['slug'],
                    "section_title": section['title'],
                    "page": page_info['slug'],
                    "page_title": page_info['title'],
                    "snippet": snippet
                })

    return jsonify({"results": results})
