"""
Vues principales du portfolio.
Toutes les données viennent de :
  - data/projects.json  → projets
  - data/config.json    → profil, compétences, contact, footer, SEO...
"""

from django.shortcuts import render
from django.http import Http404
from .utils import (
    load_config,
    load_projects,
    get_project_by_slug,
    get_all_categories,
    get_all_technologies,
    filter_projects,
)


def loutre(request):
    """Page surprise ❤️"""
    return render(request, 'loutre.html')


def cv(request):
    """Page visionneuse CV"""
    return render(request, 'cv.html')


def _base_context():
    """
    Retourne le contexte de base commun à toutes les pages
    (config complète du site + total projets).
    """
    config = load_config()
    all_projects = load_projects()
    return config, {
        'config': config,
        'total_projects': len(all_projects),
    }


def home(request):
    """
    Page d'accueil : hero section + compétences + aperçu des projets.
    """
    config, context = _base_context()
    all_projects = load_projects()

    context.update({
        'featured_projects': all_projects[:3],
        'all_techs': get_all_technologies(all_projects),
    })
    return render(request, 'home.html', context)


def project_list(request):
    """
    Page liste des projets avec filtres par catégorie et technologie.
    """
    config, context = _base_context()
    all_projects = load_projects()

    selected_category = request.GET.get('category', '').strip()
    selected_tech     = request.GET.get('tech', '').strip()
    projects          = filter_projects(all_projects, category=selected_category, tech=selected_tech)

    context.update({
        'projects':           projects,
        'categories':         get_all_categories(all_projects),
        'technologies':       get_all_technologies(all_projects),
        'selected_category':  selected_category,
        'selected_tech':      selected_tech,
        'total_count':        len(projects),
    })
    return render(request, 'projects/list.html', context)


def project_detail(request, slug):
    """
    Page détail d'un projet : description complète + galerie + highlights.
    """
    project = get_project_by_slug(slug)

    if project is None:
        raise Http404("Projet introuvable.")

    config, context = _base_context()
    all_projects  = load_projects()
    current_index = project.get('id', 0)

    context.update({
        'project':      project,
        'prev_project': all_projects[current_index - 1] if current_index > 0 else None,
        'next_project': all_projects[current_index + 1] if current_index < len(all_projects) - 1 else None,
    })
    return render(request, 'projects/detail.html', context)
