"""Markdown converter for Drupal Aggregator."""
from typing import List, Dict, Any
from pathlib import Path
from drupal_news.utils.timebox import format_datetime
from drupal_news.utils.io_safe import safe_write_text


def generate_parsed_md(
    items: List[Dict[str, Any]],
    timeframe_days: int,
    timezone: str,
    max_rows: int = 200,
    period_label: str = None
) -> str:
    """
    Generate parsed.md with raw collected data.

    Args:
        items: List of news items
        timeframe_days: Number of days covered
        timezone: Timezone name
        max_rows: Maximum rows in tables
        period_label: Period label (e.g., "Weekly", "Biweekly")

    Returns:
        Markdown text
    """
    md_lines = []

    # Header
    if period_label is None:
        from utils.timebox import get_period_label
        period_label = get_period_label(timeframe_days)

    md_lines.append(f"# Drupal {period_label} - Parsed Data\n")
    md_lines.append(f"**Timeframe:** Last {timeframe_days} days")
    md_lines.append(f"**Timezone:** {timezone}")
    md_lines.append(f"**Total Items:** {len(items)}\n")

    # Group by source type
    rss_items = [item for item in items if item.get("source_type") == "rss"]
    page_items = [item for item in items if item.get("source_type") == "page"]

    # RSS Items
    if rss_items:
        md_lines.append("## RSS Feed Items\n")
        md_lines.append("| URL | Title | Description |")
        md_lines.append("|-----|-------|-------------|")

        for item in rss_items[:max_rows]:
            url = item.get("url", "")
            title = item.get("title", "").replace("|", "\\|")
            desc = item.get("description", "").replace("|", "\\|")[:100]

            md_lines.append(f"| {url} | {title} | {desc} |")

        if len(rss_items) > max_rows:
            md_lines.append(f"\n*Showing {max_rows} of {len(rss_items)} items*\n")

    # Page Items
    if page_items:
        md_lines.append("\n## Web Page Items\n")
        md_lines.append("| URL | Title | Description |")
        md_lines.append("|-----|-------|-------------|")

        for item in page_items[:max_rows]:
            url = item.get("url", "")
            title = item.get("title", "").replace("|", "\\|")
            desc = item.get("description", "").replace("|", "\\|")[:100]

            md_lines.append(f"| {url} | {title} | {desc} |")

        if len(page_items) > max_rows:
            md_lines.append(f"\n*Showing {max_rows} of {len(page_items)} items*\n")

    # Summary stats
    md_lines.append("\n## Statistics\n")
    md_lines.append(f"- RSS items: {len(rss_items)}")
    md_lines.append(f"- Page items: {len(page_items)}")
    md_lines.append(f"- Total: {len(items)}")

    return "\n".join(md_lines)


def write_parsed_md(items: List[Dict[str, Any]], output_path: Path, **kwargs):
    """
    Write parsed.md file.

    Args:
        items: List of news items
        output_path: Output file path
        **kwargs: Additional arguments for generate_parsed_md
    """
    markdown = generate_parsed_md(items, **kwargs)
    safe_write_text(markdown, output_path)


def generate_summary_md(
    summary_text: str,
    metadata: Dict[str, Any]
) -> str:
    """
    Generate summary.md with AI summary and metadata.

    Args:
        summary_text: AI-generated summary
        metadata: Metadata dictionary (should include period_label)

    Returns:
        Markdown text
    """
    md_lines = []

    # Header
    period_label = metadata.get("period_label", "Weekly")
    md_lines.append(f"# Drupal {period_label} Summary\n")

    # Metadata
    if metadata.get("date"):
        md_lines.append(f"**Date:** {metadata['date']}")
        md_lines.append("\n")
    if metadata.get("timeframe_days"):
        md_lines.append(f"**Timeframe:** Last {metadata['timeframe_days']} days")
        md_lines.append("\n")
    if metadata.get("timezone"):
        md_lines.append(f"**Timezone:** {metadata['timezone']}")
        md_lines.append("\n")
    if metadata.get("provider"):
        md_lines.append(f"**AI Provider:** {metadata['provider']}")
        md_lines.append("\n")
    if metadata.get("model"):
        md_lines.append(f"**Model:** {metadata['model']}")

    md_lines.append("\n---\n")

    # Summary content
    md_lines.append(summary_text)

    # Footer
    md_lines.append("\n---\n")
    md_lines.append("*Generated by Drupal News Aggregator*")
    md_lines.append("\n")
    if metadata.get("generated_at"):
        md_lines.append(f"*Generated at: {metadata['generated_at']}*")

    return "\n".join(md_lines)


def write_summary_md(summary_text: str, output_path: Path, metadata: Dict[str, Any]):
    """
    Write summary.md file.

    Args:
        summary_text: AI-generated summary
        output_path: Output file path
        metadata: Metadata dictionary
    """
    markdown = generate_summary_md(summary_text, metadata)
    safe_write_text(markdown, output_path)


def items_to_text(items: List[Dict[str, Any]], max_items: int = 200) -> str:
    """
    Convert items to plain text format for AI processing.

    Args:
        items: List of news items
        max_items: Maximum items to include

    Returns:
        Formatted text
    """
    lines = []

    for i, item in enumerate(items[:max_items], 1):
        lines.append(f"{i}. {item.get('title', 'Untitled')}")
        lines.append(f"   URL: {item.get('url', '')}")

        if item.get("description"):
            lines.append(f"   Description: {item['description'][:200]}")

        if item.get("date"):
            lines.append(f"   Date: {item['date']}")

        lines.append("")  # Empty line

    return "\n".join(lines)
