from django.shortcuts import render
from django.http import Http404
import frontmatter
import markdown
from pathlib import Path
from components.models import Vote


def get_blog_posts(tag_filter=None):
    """Read all blog posts from the markdown files."""
    blog_dir = Path(__file__).parent / 'posts'
    posts = []
    
    if not blog_dir.exists():
        return posts
    
    for md_file in blog_dir.glob('*.md'):
        with open(md_file, 'r', encoding='utf-8') as f:
            post = frontmatter.load(f)
            
            # Only include published posts
            if post.get('published', False):
                # Get tags (can be list or single string)
                tags = post.get('tags', [])
                if isinstance(tags, str):
                    tags = [tags]
                
                # Filter by tag if specified
                if tag_filter and tag_filter not in tags:
                    continue
                
                post_data = {
                    'slug': post.get('slug', md_file.stem),
                    'title': post.get('title', 'Untitled'),
                    'date': post.get('date'),
                    'author': post.get('author', 'Anonymous'),
                    'summary': post.get('summary', post.get('description', '')),
                    'content': post.content,
                    'tags': tags,
                }
                posts.append(post_data)
    
    # Sort by date (newest first)
    posts.sort(key=lambda x: x['date'] if x['date'] else '', reverse=True)
    return posts


def get_all_tags():
    """Get all unique tags from all published posts."""
    posts = get_blog_posts()
    tags = set()
    for post in posts:
        tags.update(post.get('tags', []))
    return sorted(tags)


def blog_list(request):
    """Display list of all blog posts."""
    all_posts = get_blog_posts()
    all_tags = get_all_tags()
    
    # Separate posts into Articles (no "computing" tag) and Developer Notes (with "computing" tag)
    articles = [post for post in all_posts if "computing" not in post.get('tags', [])]
    developer_notes = [post for post in all_posts if "computing" in post.get('tags', [])]
    
    context = {
        'articles': articles,
        'developer_notes': developer_notes,
        'all_tags': all_tags,
    }
    return render(request, 'blog/blog_list.html', context)


def blog_by_tag(request, tag):
    """Display blog posts filtered by tag."""
    posts = get_blog_posts(tag_filter=tag)
    all_tags = get_all_tags()
    context = {
        'posts': posts,
        'all_tags': all_tags,
        'current_tag': tag,
    }
    return render(request, 'blog/blog_list.html', context)


def blog_detail(request, slug):
    """Display a single blog post."""
    posts = get_blog_posts()
    
    # Find the post with the matching slug
    post = None
    for p in posts:
        if p['slug'] == slug:
            post = p
            break
    
    if not post:
        raise Http404("Blog post not found")
    
    # Convert markdown to HTML
    md = markdown.Markdown(extensions=['extra', 'codehilite', 'fenced_code'])
    post['content_html'] = md.convert(post['content'])
    
    # Get vote count for this blog post
    try:
        vote = Vote.objects.get(content_type='blog', content_id=slug)
        post['vote_count'] = vote.vote_count
        post['has_voted'] = request.session.session_key in vote.voted_sessions if request.session.session_key else False
    except Vote.DoesNotExist:
        post['vote_count'] = 0
        post['has_voted'] = False
    
    context = {
        'post': post,
    }
    return render(request, 'blog/blog_detail.html', context)
