#!/usr/bin/env python3
"""
Blog Post Publisher v2
Publishes HTML blog posts to the website via API or file system.
"""

import argparse
import json
import os
import sys
from datetime import datetime
from pathlib import Path

def publish_post(title: str, content: str, slug: str = None, 
                 description: str = None, keywords: str = None) -> dict:
    """
    Publish a blog post.
    
    Args:
        title: Post title
        content: HTML content
        slug: URL slug (auto-generated if not provided)
        description: Meta description
        keywords: Meta keywords
    
    Returns:
        dict with publication status and details
    """
    
    # Auto-generate slug if not provided
    if not slug:
        slug = title.lower().replace(' ', '-').replace('?', '').replace('!', '')[:60]
    
    # Ensure slug is URL-safe
    slug = ''.join(c for c in slug if c.isalnum() or c == '-')
    
    # Generate post metadata
    post_data = {
        "title": title,
        "slug": slug,
        "content": content,
        "description": description or f"Hot deal alert: {title}",
        "keywords": keywords or "deals, coupons, savings, discounts",
        "published_at": datetime.now().isoformat(),
        "status": "published"
    }
    
    # Output directory for posts
    output_dir = Path(__file__).parent.parent / "posts"
    output_dir.mkdir(exist_ok=True)
    
    # Save post as JSON (for API integration later)
    post_file = output_dir / f"{slug}.json"
    with open(post_file, 'w') as f:
        json.dump(post_data, f, indent=2)
    
    # Save post as HTML
    html_file = output_dir / f"{slug}.html"
    with open(html_file, 'w') as f:
        f.write(content)
    
    return {
        "success": True,
        "slug": slug,
        "json_path": str(post_file),
        "html_path": str(html_file),
        "published_at": post_data["published_at"]
    }

def main():
    parser = argparse.ArgumentParser(description='Publish a blog post')
    parser.add_argument('--title', required=True, help='Post title')
    parser.add_argument('--content', required=True, help='HTML content or path to HTML file')
    parser.add_argument('--slug', help='URL slug (auto-generated if not provided)')
    parser.add_argument('--description', help='Meta description')
    parser.add_argument('--keywords', help='Meta keywords')
    parser.add_argument('--content-file', action='store_true', 
                        help='Treat content as file path instead of raw HTML')
    
    args = parser.parse_args()
    
    # Load content from file if specified
    content = args.content
    if args.content_file or (args.content.endswith('.html') and os.path.exists(args.content)):
        with open(args.content, 'r') as f:
            content = f.read()
    
    # Publish the post
    result = publish_post(
        title=args.title,
        content=content,
        slug=args.slug,
        description=args.description,
        keywords=args.keywords
    )
    
    # Output result as JSON
    print(json.dumps(result, indent=2))
    
    return 0 if result["success"] else 1

if __name__ == "__main__":
    sys.exit(main())