#!/usr/bin/env python3
"""
Export hits/<topic>.jsonl into:
  reports/EKOS-<Topic>.csv          — flat, all hits, chronological
  reports/EKOS-<Topic>-Rapor.docx   — formatted Word report (TOC, top-30 smoking
                                       guns, per-year sections with snippets)

Examples:
  python scripts/04_export.py
  python scripts/04_export.py --topic Kirim --out-dir /home/salva/Documents/EKOS-out
"""
import argparse
import csv
import json
from collections import Counter, defaultdict
from datetime import datetime
from pathlib import Path

from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt, RGBColor, Cm

HERE = Path(__file__).resolve().parent.parent

MONTH_TR = {
    "ocak": ("Ocak", 1), "subat": ("Şubat", 2), "şubat": ("Şubat", 2),
    "mart": ("Mart", 3), "nisan": ("Nisan", 4), "mayis": ("Mayıs", 5),
    "mayıs": ("Mayıs", 5), "haziran": ("Haziran", 6), "temmuz": ("Temmuz", 7),
    "agustos": ("Ağustos", 8), "ağustos": ("Ağustos", 8),
    "eylul": ("Eylül", 9), "eylül": ("Eylül", 9), "ekim": ("Ekim", 10),
    "kasim": ("Kasım", 11), "kasım": ("Kasım", 11),
    "aralik": ("Aralık", 12), "aralık": ("Aralık", 12),
    "kanunusani": ("Ocak", 1), "kanunuevvel": ("Aralık", 12),
    "tesrinievvel": ("Ekim", 10), "tesrinisani": ("Kasım", 11),
}


def date_key(h):
    """Sort key: (year, month_num, day)."""
    m = MONTH_TR.get(h["month"].lower(), (h["month"], 99))[1]
    try:
        d = int(h["day"])
    except Exception:
        d = 99
    return (int(h["year"]), m, d)


def load_hits(path):
    hits = []
    with path.open(encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                hits.append(json.loads(line))
    return hits


def write_csv(path, hits):
    """All hits flat. Sort: chronological, then weight DESC within same date."""
    fields = ["year", "month", "day", "slug", "page",
              "keyword", "match", "weight",
              "priority_window", "window_reason", "snippet", "url"]
    sorted_hits = sorted(hits, key=lambda h: (date_key(h), -h.get("weight", 0)))
    with path.open("w", encoding="utf-8", newline="") as f:
        w = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
        w.writeheader()
        for h in sorted_hits:
            row = dict(h)
            row["snippet"] = (row.get("snippet") or "").replace("\n", " ").strip()
            w.writerow(row)
    return len(sorted_hits)


def _set_cell_bold(cell, bold=True):
    for p in cell.paragraphs:
        for r in p.runs:
            r.bold = bold


def write_docx(path, hits, topic):
    doc = Document()

    # Margins
    for s in doc.sections:
        s.top_margin = Cm(2.0)
        s.bottom_margin = Cm(2.0)
        s.left_margin = Cm(2.0)
        s.right_margin = Cm(2.0)

    # Title
    t = doc.add_heading(f"EKOS — {topic} Bulguları", level=0)
    t.alignment = WD_ALIGN_PARAGRAPH.CENTER

    sub = doc.add_paragraph()
    sub.alignment = WD_ALIGN_PARAGRAPH.CENTER
    r = sub.add_run("İstanbul Üniversitesi NEK Gazete Arşivi (1928-1942)")
    r.italic = True; r.font.size = Pt(11)

    # Stats overview
    by_year = defaultdict(list)
    for h in hits:
        by_year[h["year"]].append(h)
    kw_counter = Counter(h["keyword"] for h in hits)
    slug_counter = Counter(h["slug"] for h in hits)
    priority_hits = [h for h in hits if h.get("priority_window")]

    doc.add_paragraph()
    p = doc.add_paragraph()
    p.add_run("Üretim tarihi: ").bold = True
    p.add_run(datetime.now().strftime("%Y-%m-%d %H:%M"))
    p = doc.add_paragraph()
    p.add_run("Toplam vuruş: ").bold = True
    p.add_run(f"{len(hits)}  ")
    p.add_run("Öncelikli pencere içinde: ").bold = True
    p.add_run(f"{len(priority_hits)}")
    p = doc.add_paragraph()
    p.add_run("Yıl aralığı: ").bold = True
    yrs = sorted(by_year)
    p.add_run(f"{yrs[0]} – {yrs[-1]}  ")
    p.add_run("Gazete sayısı: ").bold = True
    p.add_run(f"{len(slug_counter)}")

    # Yearly distribution table
    doc.add_heading("Yıllara Göre Dağılım", level=1)
    tbl = doc.add_table(rows=1, cols=3)
    tbl.style = "Light Grid Accent 1"
    hdr = tbl.rows[0].cells
    hdr[0].text = "Yıl"; hdr[1].text = "Toplam"; hdr[2].text = "Öncelikli"
    for c in hdr: _set_cell_bold(c, True)
    for y in yrs:
        row = tbl.add_row().cells
        row[0].text = y
        row[1].text = str(len(by_year[y]))
        row[2].text = str(sum(1 for h in by_year[y] if h.get("priority_window")))

    # Keyword distribution
    doc.add_heading("Anahtar Kelime Dağılımı (top 20)", level=1)
    tbl = doc.add_table(rows=1, cols=2)
    tbl.style = "Light Grid Accent 1"
    hdr = tbl.rows[0].cells
    hdr[0].text = "Anahtar"; hdr[1].text = "Sayı"
    for c in hdr: _set_cell_bold(c, True)
    for kw, n in kw_counter.most_common(20):
        row = tbl.add_row().cells
        row[0].text = kw
        row[1].text = str(n)

    # Slug productivity
    doc.add_heading("En Verimli Gazeteler", level=1)
    tbl = doc.add_table(rows=1, cols=2)
    tbl.style = "Light Grid Accent 1"
    hdr = tbl.rows[0].cells
    hdr[0].text = "Gazete"; hdr[1].text = "Vuruş"
    for c in hdr: _set_cell_bold(c, True)
    for slug, n in slug_counter.most_common(15):
        row = tbl.add_row().cells
        row[0].text = slug
        row[1].text = str(n)

    # Top scored hits
    doc.add_page_break()
    doc.add_heading("En Yüksek Skorlu 30 Vuruş", level=1)
    doc.add_paragraph(
        "Skorlama: temel kelime ağırlığı + öncelikli pencere bonusu. "
        "Yüksek skorlu vuruşlar manuel okumada ilk öncelik."
    ).italic = True
    top = sorted(hits, key=lambda h: -h.get("weight", 0))[:30]
    for i, h in enumerate(top, 1):
        m_pretty = MONTH_TR.get(h["month"].lower(), (h["month"], 0))[0]
        head = doc.add_paragraph()
        run = head.add_run(f"{i}. {h['slug']} — {h['year']} {m_pretty} {h['day']} — s. {h['page']}")
        run.bold = True; run.font.size = Pt(11)

        meta = doc.add_paragraph()
        meta.add_run("Anahtar: ").bold = True
        meta.add_run(f"{h['keyword']}  ")
        meta.add_run("Eşleşme: ").bold = True
        meta.add_run(f"{h['match']}  ")
        meta.add_run("Skor: ").bold = True
        meta.add_run(f"{h.get('weight', 0)}")
        if h.get("priority_window"):
            wr = h.get("window_reason") or ""
            run2 = meta.add_run(f"  [öncelikli: {wr[:60]}]")
            run2.italic = True
            run2.font.color.rgb = RGBColor(0xC0, 0x39, 0x2B)

        sn = doc.add_paragraph()
        sn.paragraph_format.left_indent = Cm(0.6)
        sn_run = sn.add_run(h.get("snippet", ""))
        sn_run.italic = True; sn_run.font.size = Pt(10)

        url_p = doc.add_paragraph()
        url_p.paragraph_format.left_indent = Cm(0.6)
        url_run = url_p.add_run(f"PDF: {h['url']}")
        url_run.font.size = Pt(8)
        url_run.font.color.rgb = RGBColor(0x55, 0x55, 0x55)

    # Per-year sections
    for year in yrs:
        doc.add_page_break()
        year_hits = sorted(by_year[year],
                           key=lambda h: (date_key(h), -h.get("weight", 0)))
        prio = sum(1 for h in year_hits if h.get("priority_window"))
        doc.add_heading(f"{year}  ({len(year_hits)} vuruş, {prio} öncelikli)",
                        level=1)

        # Quick keyword summary for the year
        yk = Counter(h["keyword"] for h in year_hits)
        s = doc.add_paragraph()
        s.add_run("Anahtar dağılımı: ").bold = True
        s.add_run(", ".join(f"{k}({v})" for k, v in yk.most_common(8)))

        # Group by date
        by_date = defaultdict(list)
        for h in year_hits:
            key = (h["year"], h["month"], h["day"])
            by_date[key].append(h)

        for dk in sorted(by_date, key=lambda k: (
                int(k[0]),
                MONTH_TR.get(k[1].lower(), (k[1], 99))[1],
                int(k[2]) if str(k[2]).isdigit() else 99)):
            y, m, d = dk
            m_pretty = MONTH_TR.get(m.lower(), (m, 0))[0]
            doc.add_heading(f"{y} {m_pretty} {d}", level=3)
            for h in by_date[dk]:
                p = doc.add_paragraph()
                p.add_run(f"{h['slug']}  ").bold = True
                p.add_run(f"s.{h['page']} — ")
                kr = p.add_run(h["keyword"])
                kr.bold = True
                if h.get("priority_window"):
                    kr.font.color.rgb = RGBColor(0xC0, 0x39, 0x2B)
                p.add_run(f"  (skor {h.get('weight', 0)})")

                sn = doc.add_paragraph()
                sn.paragraph_format.left_indent = Cm(0.5)
                sr = sn.add_run(h.get("snippet", ""))
                sr.italic = True; sr.font.size = Pt(9)

    # Footer
    doc.add_page_break()
    f = doc.add_paragraph()
    f.alignment = WD_ALIGN_PARAGRAPH.CENTER
    fr = f.add_run(f"Otomatik üretildi: ekos-gazete-search skill, "
                   f"{datetime.now().strftime('%Y-%m-%d %H:%M')}")
    fr.italic = True; fr.font.size = Pt(9)

    doc.save(str(path))


def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--hits", default=str(HERE / "hits/kirim.jsonl"))
    ap.add_argument("--topic", default="Kirim")
    ap.add_argument("--out-dir", default=str(HERE / "reports"))
    args = ap.parse_args()

    hits_path = Path(args.hits)
    if not hits_path.exists() or hits_path.stat().st_size == 0:
        print(f"[!] No hits at {hits_path}")
        return

    hits = load_hits(hits_path)
    print(f"Loaded {len(hits)} hits from {hits_path}")

    out_dir = Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    csv_path = out_dir / f"EKOS-{args.topic}.csv"
    docx_path = out_dir / f"EKOS-{args.topic}-Rapor.docx"

    n = write_csv(csv_path, hits)
    print(f"  ✓ CSV  ({n} rows) → {csv_path}")

    write_docx(docx_path, hits, args.topic)
    print(f"  ✓ DOCX        → {docx_path}")


if __name__ == "__main__":
    main()
