"""Combined output formatter for Drupal Aggregator.

This module combines markdown generation and PDF conversion into a single interface.
"""

from typing import List, Dict, Any, Optional
from pathlib import Path
import markdown

# Import consolidated utilities
from drupal_news.utils.consolidated_utils import safe_write_text, get_period_label


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:
        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)


# PDF generation functions
def markdown_to_pdf(
    markdown_path: Path,
    pdf_path: Path,
    title: Optional[str] = None,
    css_style: Optional[str] = None
) -> bool:
    """
    Convert markdown file to PDF.

    Args:
        markdown_path: Path to input markdown file
        pdf_path: Path to output PDF file
        title: Optional document title
        css_style: Optional custom CSS styles

    Returns:
        True if successful, False otherwise
    """
    try:
        from weasyprint import HTML, CSS
        from weasyprint.text.fonts import FontConfiguration
    except ImportError:
        print("Error: weasyprint not installed. Install with: pip install weasyprint")
        return False

    try:
        # Read markdown content
        with open(markdown_path, 'r', encoding='utf-8') as f:
            md_content = f.read()

        # Convert markdown to HTML
        md = markdown.Markdown(extensions=[
            'extra',
            'codehilite',
            'tables',
            'toc',
            'fenced_code'
        ])
        html_body = md.convert(md_content)

        # Get title from metadata or use provided title
        doc_title = title or "Drupal Aggregator Summary"

        # Default CSS styling
        default_css = """
        @page {
            size: A4;
            margin: 2cm;
            @bottom-center {
                content: "Page " counter(page) " of " counter(pages);
                font-size: 9pt;
                color: #666;
            }
        }

        body {
            font-family: "DejaVu Sans", Arial, sans-serif;
            font-size: 11pt;
            line-height: 1.6;
            color: #333;
            max-width: 100%;
        }

        h1 {
            color: #0678BE;
            font-size: 24pt;
            margin-top: 0;
            margin-bottom: 0.5em;
            border-bottom: 2px solid #0678BE;
            padding-bottom: 0.3em;
        }

        h2 {
            color: #0678BE;
            font-size: 18pt;
            margin-top: 1.5em;
            margin-bottom: 0.5em;
            border-bottom: 1px solid #ccc;
            padding-bottom: 0.2em;
        }

        h3 {
            color: #333;
            font-size: 14pt;
            margin-top: 1em;
            margin-bottom: 0.5em;
        }

        h4, h5, h6 {
            color: #555;
            margin-top: 0.8em;
            margin-bottom: 0.4em;
        }

        p {
            margin: 0.5em 0;
            text-align: justify;
        }

        a {
            color: #0678BE;
            text-decoration: none;
        }

        a:hover {
            text-decoration: underline;
        }

        ul, ol {
            margin: 0.5em 0;
            padding-left: 2em;
        }

        li {
            margin: 0.3em 0;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            margin: 1em 0;
            font-size: 10pt;
        }

        th {
            background-color: #0678BE;
            color: white;
            font-weight: bold;
            padding: 8px;
            text-align: left;
            border: 1px solid #ddd;
        }

        td {
            padding: 6px 8px;
            border: 1px solid #ddd;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        code {
            background-color: #f4f4f4;
            padding: 2px 4px;
            border-radius: 3px;
            font-family: "DejaVu Sans Mono", monospace;
            font-size: 9pt;
        }

        pre {
            background-color: #f4f4f4;
            padding: 1em;
            border-radius: 5px;
            overflow-x: auto;
            border-left: 3px solid #0678BE;
        }

        pre code {
            background-color: transparent;
            padding: 0;
        }

        blockquote {
            border-left: 4px solid #0678BE;
            margin: 1em 0;
            padding-left: 1em;
            color: #666;
            font-style: italic;
        }

        hr {
            border: none;
            border-top: 1px solid #ccc;
            margin: 2em 0;
        }

        .metadata {
            background-color: #f9f9f9;
            padding: 1em;
            border-radius: 5px;
            margin-bottom: 2em;
            font-size: 9pt;
            color: #666;
        }
        """

        # Use custom CSS if provided, otherwise use default
        final_css = css_style or default_css

        # Create full HTML document
        html_doc = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>{doc_title}</title>
        </head>
        <body>
            {html_body}
        </body>
        </html>
        """

        # Configure fonts
        font_config = FontConfiguration()

        # Generate PDF
        HTML(string=html_doc).write_pdf(
            pdf_path,
            stylesheets=[CSS(string=final_css, font_config=font_config)],
            font_config=font_config
        )

        return True

    except Exception as e:
        print(f"PDF generation failed: {e}")
        return False


def generate_summary_pdf(
    run_dir: Path,
    markdown_filename: str = "summary.md",
    pdf_filename: str = "summary.pdf",
    period_label: str = "Weekly"
) -> Optional[Path]:
    """
    Generate PDF from summary markdown in run directory.

    Args:
        run_dir: Run directory path
        markdown_filename: Name of markdown file (default: summary.md)
        pdf_filename: Name of output PDF file (default: summary.pdf)
        period_label: Period label (e.g., "Weekly", "Biweekly")

    Returns:
        Path to generated PDF, or None if failed
    """
    markdown_path = run_dir / markdown_filename
    pdf_path = run_dir / pdf_filename

    if not markdown_path.exists():
        print(f"Error: Markdown file not found: {markdown_path}")
        return None

    # Extract title from run directory name
    title = f"Drupal {period_label} Summary - {run_dir.name}"

    if markdown_to_pdf(markdown_path, pdf_path, title=title):
        return pdf_path
    else:
        return None