import os
import json
from datetime import datetime
from pathlib import Path
from typing import List, Optional


def get_documents_folder() -> Path:
    """Get the Documents folder path."""
    if os.name == "nt":
        documents = Path(os.environ.get("USERPROFILE", "~")) / "Documents"
    else:
        documents = Path.home() / "Documents"
    return documents


def get_export_folder() -> Path:
    """Get or create the ACHEM export folder."""
    export_dir = get_documents_folder() / "ACHEM"
    export_dir.mkdir(parents=True, exist_ok=True)
    return export_dir


def sanitize_filename(text: str) -> str:
    """Sanitize text for use as filename."""
    invalid_chars = '<>:"/\\|?*'
    for char in invalid_chars:
        text = text.replace(char, "_")
    return text[:50]


def export_summary(
    summary: str,
    query: str,
    keywords: List[str] = None,
    source_count: int = 0,
    format: str = "md",
) -> bool:
    """Export summary to a file in Documents folder.

    Args:
        summary: The summary text to export
        query: The search query
        keywords: List of keywords
        source_count: Number of sources used
        format: 'md' for Markdown or 'txt' for plain text

    Returns:
        True if successful, False otherwise
    """
    try:
        export_dir = get_export_folder()
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        safe_query = sanitize_filename(query)
        filename = f"{timestamp}_{safe_query}.{format}"
        filepath = export_dir / filename

        content = generate_export_content(
            summary=summary,
            query=query,
            keywords=keywords or [],
            source_count=source_count,
            format=format,
        )

        with open(filepath, "w", encoding="utf-8") as f:
            f.write(content)

        print(f"\n✅ Summary exported to: {filepath}\n")
        return True

    except Exception as e:
        print(f"\n❌ Export failed: {e}\n")
        return False


def generate_export_content(
    summary: str,
    query: str,
    keywords: List[str],
    source_count: int,
    format: str,
) -> str:
    """Generate the content for export file."""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    if format == "md":
        content = f"""# Research Summary: {query}

**Date:** {timestamp}
**Sources:** {source_count}
**Keywords:** {", ".join(keywords) if keywords else "N/A"}

---

## Summary

{summary}

---

*Generated by ACHEM v1.0.0*
"""
    else:
        content = f"""
================================================================================
                    RESEARCH SUMMARY: {query}
================================================================================

Date: {timestamp}
Sources: {source_count}
Keywords: {", ".join(keywords) if keywords else "N/A"}

--------------------------------------------------------------------------------
                                 SUMMARY
--------------------------------------------------------------------------------

{summary}

--------------------------------------------------------------------------------
                    Generated by ACHEM v1.0.0
================================================================================
"""

    return content


def list_exports() -> List[Path]:
    """List all exported summaries."""
    export_dir = get_export_folder()
    return sorted(export_dir.glob("*.md")) + sorted(export_dir.glob("*.txt"))
