import re

from django.shortcuts import render, get_object_or_404
from .models import PortfolioItem, PortfolioCategory


def portfolio_list(request):
    category_slug = request.GET.get('category')
    items = PortfolioItem.objects.filter(is_active=True)
    categories = PortfolioCategory.objects.all()
    active_category = None

    if category_slug:
        active_category = get_object_or_404(PortfolioCategory, slug=category_slug)
        items = items.filter(category=active_category)

    return render(request, 'public/portfolio.html', {
        'items': items,
        'categories': categories,
        'active_category': active_category,
    })


def _split_body(html):
    """Cut the writeup after its first paragraph, so the summary box always
    lands in the same place however long the piece is. A body of one block
    comes back whole, with nothing after the box."""
    if not html:
        return '', ''
    parts = [p for p in re.split(r'(?i)(?<=</p>)', html) if p.strip()]
    if len(parts) < 2:
        return html, ''
    return parts[0], ''.join(parts[1:])


def portfolio_detail(request, slug):
    item = get_object_or_404(PortfolioItem, slug=slug, is_active=True)
    # Increment view counter without triggering score recomputation
    PortfolioItem.objects.filter(pk=item.pk).update(view_count=item.view_count + 1)
    related = PortfolioItem.objects.filter(is_active=True).exclude(pk=item.pk).order_by('-created_at')[:5]
    technologies = [t.strip() for t in item.technologies.split(',') if t.strip()] if item.technologies else []
    gallery = item.gallery.filter(is_active=True)[:10]
    body_top, body_bottom = _split_body(item.full_description)
    return render(request, 'public/portfolio_detail.html', {
        'item': item,
        'related': related,
        'technologies': technologies,
        'gallery': gallery,
        'body_top': body_top,
        'body_bottom': body_bottom,
    })
