"""
core/export.py
- Export to PDF / TXT / CSV (ដោះស្រាយបញ្ហា horizontal space)
"""

import io
from datetime import datetime

# =====================================================
# Unicode sanitizer for FPDF's default Helvetica font
# =====================================================
_REPLACEMENTS = {
    "\u2014": "-",   # em dash
    "\u2013": "-",   # en dash
    "\u2018": "'",   # left single quote
    "\u2019": "'",   # right single quote
    "\u201c": '"',   # left double quote
    "\u201d": '"',   # right double quote
    "\u2026": "...", # ellipsis
    "\u2022": "*",   # bullet
    "\u00b7": "*",   # middle dot
    "\u2192": "->",  # right arrow
    "\u2190": "<-",  # left arrow
    "\u2713": "v",   # check
    "\u2717": "x",   # cross
    "\u2b50": "*",   # star
    "\u2764": "<3",  # heart
    "\u00a0": " ",   # nbsp
    "\u200b": "",    # zero-width space
    "\u200d": "",    # zero-width joiner
}

def _s(text) -> str:
    """Make text safe for FPDF latin-1 encoding"""
    if text is None:
        return ""
    text = str(text)
    for k, v in _REPLACEMENTS.items():
        text = text.replace(k, v)
    # Drop remaining unsupported chars
    return text.encode("latin-1", "replace").decode("latin-1")

def _truncate_long_words(text: str, max_len: int = 80) -> str:
    """កាត់ពាក្យវែងៗដែលគ្មានចន្លោះ"""
    words = text.split()
    result = []
    for word in words:
        if len(word) > max_len:
            # បំបែកពាក្យវែងជាកំណាត់
            for i in range(0, len(word), max_len):
                result.append(word[i:i+max_len])
        else:
            result.append(word)
    return " ".join(result)

# =====================================================
# TXT export (ដូចដើម)
# =====================================================
def to_txt(video: dict, ai: dict | None = None) -> bytes:
    lines = [
        "=" * 60,
        "YT Analyzer Pro - Report",
        f"Generated: {datetime.now():%Y-%m-%d %H:%M:%S}",
        "=" * 60,
        "",
        f"Title       : {video.get('title','')}",
        f"Channel     : {video.get('channel_title','')}",
        f"URL         : {video.get('url','')}",
        f"Published   : {video.get('published_at','')}",
        f"Duration    : {video.get('duration','')}",
        f"Views       : {video.get('views_fmt','')}",
        f"Likes       : {video.get('likes_fmt','')}",
        f"Comments    : {video.get('comments_fmt','')}",
        "",
        "--- DESCRIPTION ---",
        video.get("description", ""),
        "",
        "--- TAGS ---",
        ", ".join(video.get("tags", [])),
    ]
    if ai:
        lines += ["", "=" * 60, "AI ANALYSIS", "=" * 60, ""]
        lines += [
            f"Score       : {ai.get('score','')}",
            f"Summary     : {ai.get('summary','')}",
        ]
        for key, label in [
            ("strengths", "STRENGTHS"),
            ("weaknesses", "WEAKNESSES"),
            ("recommended_titles", "RECOMMENDED TITLES"),
            ("recommended_tags", "RECOMMENDED TAGS"),
            ("recommended_hashtags", "RECOMMENDED HASHTAGS"),
            ("keywords", "KEYWORDS"),
            ("long_tail_keywords", "LONG-TAIL KEYWORDS"),
            ("content_ideas", "CONTENT IDEAS"),
        ]:
            items = ai.get(key, [])
            if items:
                lines.append(f"\n--- {label} ---")
                for it in items:
                    lines.append(f"  - {it}")
        if ai.get("recommended_description"):
            lines += [
                "\n--- RECOMMENDED DESCRIPTION ---",
                ai["recommended_description"],
            ]
    return "\n".join(lines).encode("utf-8")

# =====================================================
# CSV export (ដូចដើម)
# =====================================================
def to_csv_bytes(rows: list[dict], headers: list[str]) -> bytes:
    import csv
    buf = io.StringIO()
    w = csv.DictWriter(buf, fieldnames=headers, extrasaction="ignore")
    w.writeheader()
    for r in rows:
        w.writerow(r)
    return buf.getvalue().encode("utf-8-sig")

# =====================================================
# PDF export (កែសម្រួលដើម្បីដោះស្រាយ horizontal space)
# =====================================================
def to_pdf(video: dict, ai: dict | None = None) -> bytes:
    from fpdf import FPDF

    pdf = FPDF()
    pdf.set_auto_page_break(auto=True, margin=15)
    pdf.add_page()

    # Header
    pdf.set_fill_color(102, 126, 234)
    pdf.set_text_color(255, 255, 255)
    pdf.set_font("Helvetica", "B", 18)
    pdf.cell(0, 14, _s("YT Analyzer Pro - Report"), ln=True, align="C", fill=True)
    pdf.ln(4)

    pdf.set_text_color(40, 40, 40)
    pdf.set_font("Helvetica", "", 11)

    def row(label, value):
        pdf.set_font("Helvetica", "B", 11)
        pdf.cell(38, 8, _s(f"{label}:"), ln=0)
        pdf.set_font("Helvetica", "", 11)
        # ប្រើ multi_cell ជាមួយទទឹងជាក់លាក់ (170mm)
        txt = _s(value if value else "-")
        txt = _truncate_long_words(txt)
        pdf.multi_cell(170, 8, txt)

    row("Title", video.get("title"))
    row("Channel", video.get("channel_title"))
    row("URL", video.get("url"))
    row("Published", video.get("published_at"))
    row("Duration", video.get("duration"))
    row("Views", video.get("views_fmt"))
    row("Likes", video.get("likes_fmt"))
    row("Comments", video.get("comments_fmt"))

    pdf.ln(2)
    pdf.set_font("Helvetica", "B", 12)
    pdf.cell(0, 8, _s("Description"), ln=True)
    pdf.set_font("Helvetica", "", 10)
    desc = _s((video.get("description") or "")[:1500])
    desc = _truncate_long_words(desc)
    pdf.multi_cell(170, 5, desc)

    tags = ", ".join(video.get("tags", []))
    if tags:
        pdf.ln(3)
        pdf.set_font("Helvetica", "B", 12)
        pdf.cell(0, 8, _s("Tags"), ln=True)
        pdf.set_font("Helvetica", "", 10)
        tags = _s(tags)
        tags = _truncate_long_words(tags)
        pdf.multi_cell(170, 5, tags)

    if ai:
        pdf.add_page()
        pdf.set_font("Helvetica", "B", 14)
        pdf.cell(0, 10, _s("AI Analysis"), ln=True)
        pdf.ln(2)
        row("Score", ai.get("score"))
        row("Summary", ai.get("summary"))
        for key, label in [
            ("strengths", "Strengths"),
            ("weaknesses", "Weaknesses"),
            ("recommended_titles", "Recommended Titles"),
            ("recommended_tags", "Recommended Tags"),
            ("recommended_hashtags", "Recommended Hashtags"),
            ("keywords", "Keywords"),
            ("long_tail_keywords", "Long-Tail Keywords"),
            ("content_ideas", "Content Ideas"),
        ]:
            items = ai.get(key, [])
            if items:
                pdf.ln(3)
                pdf.set_font("Helvetica", "B", 12)
                pdf.cell(0, 7, _s(label), ln=True)
                pdf.set_font("Helvetica", "", 10)
                for it in items:
                    txt = _s(f"- {it}")
                    txt = _truncate_long_words(txt)
                    pdf.multi_cell(170, 5, txt)
        if ai.get("recommended_description"):
            pdf.ln(3)
            pdf.set_font("Helvetica", "B", 12)
            pdf.cell(0, 7, _s("Recommended Description"), ln=True)
            pdf.set_font("Helvetica", "", 10)
            desc = _s(ai["recommended_description"])
            desc = _truncate_long_words(desc)
            pdf.multi_cell(170, 5, desc)

    return bytes(pdf.output())