"""
Output formatting for different digest formats
"""

using Dates

function format_output(digest_stories::Vector{DigestStory}, format::String, config::Dict)
    """Format digest stories according to specified format"""
    
    if format == "json"
        return format_json(digest_stories, config)
    elseif format == "markdown"
        return format_markdown(digest_stories, config)
    elseif format == "email"
        return format_email(digest_stories, config)
    else
        error("Unknown output format: $format")
    end
end

function format_json(digest_stories::Vector{DigestStory}, config::Dict)
    """Format digest as JSON"""
    
    metadata = generate_digest_metadata(digest_stories)
    
    # Convert stories to dictionary format
    stories_dict = []
    for story in digest_stories
        story_dict = Dict(
            "title" => story.title,
            "url" => story.url,
            "summary" => story.summary,
            "published" => story.published,
            "source" => story.source,
            "ai_score" => story.ai_score,
            "rank" => story.rank,
            "matched_keywords" => story.matched_keywords,
            "matched_companies" => story.matched_companies
        )
        push!(stories_dict, story_dict)
    end
    
    # Complete digest object
    digest_json = Dict(
        "digest_date" => Dates.format(today(), "yyyy-mm-dd"),
        "metadata" => metadata,
        "stories" => stories_dict
    )
    
    return JSON.json(digest_json, 2)  # Pretty print with 2-space indent
end

function format_markdown(digest_stories::Vector{DigestStory}, config::Dict)
    """Format digest as Markdown"""
    
    output = String[]
    
    # Header
    date_str = Dates.format(today(), "U d, yyyy")
    push!(output, "# AI News Digest - $date_str\\n")
    
    if isempty(digest_stories)
        push!(output, "No AI-relevant stories found for this period.\\n")
        return join(output, "")
    end
    
    # Summary stats
    metadata = generate_digest_metadata(digest_stories)
    push!(output, "*$(metadata["total_stories"]) top stories from $(metadata["sources_count"]) sources*\\n\\n")
    
    # Stories
    for story in digest_stories
        time_ago = format_time_ago(story.published)
        
        story_md = """
## $(story.rank). $(story.title)

**Source:** $(story.source) | **AI Score:** $(Int(round(story.ai_score)))/100 | **Published:** $time_ago

$(story.summary)

[Read more →]($(story.url))

"""
        push!(output, story_md)
    end
    
    # Footer with trending topics
    if !isempty(metadata["trending"]["keywords"])
        push!(output, "## 🔥 Trending Topics\\n\\n")
        trending_keywords = join(metadata["trending"]["keywords"], ", ")
        push!(output, "**Keywords:** $trending_keywords\\n\\n")
    end
    
    if !isempty(metadata["trending"]["companies"])
        trending_companies = join(metadata["trending"]["companies"], ", ")
        push!(output, "**Companies:** $trending_companies\\n\\n")
    end
    
    # Generation timestamp
    timestamp = Dates.format(now(), "yyyy-mm-dd HH:MM UTC")
    push!(output, "---\\n*Generated on $timestamp*\\n")
    
    return join(output, "")
end

function format_email(digest_stories::Vector{DigestStory}, config::Dict)
    """Format digest as HTML email"""
    
    output = String[]
    
    # HTML header
    push!(output, """
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AI News Digest</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; margin: 40px; }
        h1 { color: #333; border-bottom: 2px solid #007acc; padding-bottom: 10px; }
        h2 { color: #007acc; margin-top: 30px; }
        .meta { color: #666; font-size: 14px; margin-bottom: 10px; }
        .summary { margin: 15px 0; }
        .trending { background: #f8f9fa; padding: 15px; border-radius: 5px; margin-top: 30px; }
        a { color: #007acc; text-decoration: none; }
        a:hover { text-decoration: underline; }
    </style>
</head>
<body>
""")
    
    # Header
    date_str = Dates.format(today(), "U d, yyyy")
    push!(output, "    <h1>🤖 AI News Digest - $date_str</h1>\\n")
    
    if isempty(digest_stories)
        push!(output, "    <p>No AI-relevant stories found for this period.</p>\\n")
    else
        # Summary stats
        metadata = generate_digest_metadata(digest_stories)
        push!(output, "    <div class='meta'>$(metadata["total_stories"]) top stories from $(metadata["sources_count"]) sources</div>\\n\\n")
        
        # Stories
        for story in digest_stories
            time_ago = format_time_ago(story.published)
            
            story_html = """
    <div style="margin-bottom: 25px;">
        <h2>$(story.rank). $(escape_html(story.title))</h2>
        <div class="meta">
            <strong>Source:</strong> $(story.source) | 
            <strong>AI Score:</strong> $(Int(round(story.ai_score)))/100 | 
            <strong>Published:</strong> $time_ago
        </div>
        <div class="summary">$(escape_html(story.summary))</div>
        <a href="$(story.url)" target="_blank">Read more →</a>
    </div>

"""
            push!(output, story_html)
        end
        
        # Trending topics
        if !isempty(metadata["trending"]["keywords"]) || !isempty(metadata["trending"]["companies"])
            push!(output, "    <div class='trending'>\\n")
            push!(output, "        <h3>🔥 Trending Topics</h3>\\n")
            
            if !isempty(metadata["trending"]["keywords"])
                trending_keywords = join(metadata["trending"]["keywords"], ", ")
                push!(output, "        <p><strong>Keywords:</strong> $trending_keywords</p>\\n")
            end
            
            if !isempty(metadata["trending"]["companies"])
                trending_companies = join(metadata["trending"]["companies"], ", ")
                push!(output, "        <p><strong>Companies:</strong> $trending_companies</p>\\n")
            end
            
            push!(output, "    </div>\\n")
        end
    end
    
    # Footer
    timestamp = Dates.format(now(), "yyyy-mm-dd HH:MM UTC")
    push!(output, "    <hr style='margin-top: 40px; border: none; border-top: 1px solid #eee;'>\\n")
    push!(output, "    <p style='color: #666; font-size: 12px;'>Generated on $timestamp</p>\\n")
    
    # HTML footer
    push!(output, """
</body>
</html>
""")
    
    return join(output, "")
end

function format_time_ago(published::DateTime)
    """Format time difference as human-readable string"""
    
    diff = now() - published
    
    if Dates.value(diff) < 3600000  # Less than 1 hour (in milliseconds)
        minutes = Int(floor(Dates.value(diff) / 60000))
        return "$minutes minute$(minutes == 1 ? "" : "s") ago"
    elseif Dates.value(diff) < 86400000  # Less than 1 day
        hours = Int(floor(Dates.value(diff) / 3600000))
        return "$hours hour$(hours == 1 ? "" : "s") ago"
    else
        days = Int(floor(Dates.value(diff) / 86400000))
        return "$days day$(days == 1 ? "" : "s") ago"
    end
end

function escape_html(text::String)
    """Escape HTML special characters"""
    text = replace(text, "&" => "&amp;")
    text = replace(text, "<" => "&lt;")
    text = replace(text, ">" => "&gt;")
    text = replace(text, "\"" => "&quot;")
    text = replace(text, "'" => "&#39;")
    return text
end