#!/usr/bin/env python3
"""Your own private podcast: cut audio, set chapters, keep a feed, upload it.

  pod cut SRC OUT [--keep A-B ...] [--chapters FILE] [--title T] [--artist A] [--cover IMG]
  pod add MP3 --title T [--desc D] [--source URL]
  pod list
  pod old [--days 28]
  pod rm SLUG [SLUG ...]
  pod sync

Times: 42:00, 1:02:03, 95 (seconds), "end".
Chapters file (JSON, source timeline): [{"start": "42:00", "title": "..."}, ...]
`cut` shifts chapters onto the new timeline and drops the ones that fall into removed parts.

Library: ~/.local/share/pod (episodes.json + public/). public/ is what the listener's app sees.
Config:  ~/.config/pod/config.json
  {"base_url": "https://pod.<your-subdomain>.workers.dev",
   "title": "My podcast",
   "upload": "r2" | "command" | "none",
   "bucket": "pod",                       (upload "r2": uses `npx wrangler r2 object put/delete`)
   "command": "lftp -e 'mirror -R --delete {public} /podcast; quit' ftp.example.com"}
                                          (upload "command": runs after every change, {public} = local folder)
"""

import argparse
import datetime as dt
import email.utils
import json
import re
import shutil
import subprocess
import sys
import tempfile
import unicodedata
from pathlib import Path
from xml.sax.saxutils import escape

LIB = Path.home() / ".local" / "share" / "pod"
PUB = LIB / "public"
EPI = PUB / "episodes"
DB = LIB / "episodes.json"
REMOTE_STATE = LIB / "remote.json"
CONFIG_FILE = Path.home() / ".config" / "pod" / "config.json"
CONFIG = json.loads(CONFIG_FILE.read_text()) if CONFIG_FILE.exists() else {}
BASE_URL = CONFIG.get("base_url", "").rstrip("/")
BUCKET = CONFIG.get("bucket", "pod")
UPLOAD = CONFIG.get("upload", "none")
CONTENT_TYPES = {".xml": "application/rss+xml", ".mp3": "audio/mpeg", ".json": "application/json",
                 ".jpg": "image/jpeg", ".png": "image/png"}
FEED_TITLE = CONFIG.get("title", "Mein Hörstoff")


def die(msg):
    print(f"FEHLER: {msg}", file=sys.stderr)
    sys.exit(1)


def parse_time(s, duration=None):
    s = str(s).strip().lower()
    if s in ("end", "ende", ""):
        if duration is None:
            die("'end' braucht die Dauer")
        return duration
    parts = [float(p) for p in s.split(":")]
    sec = 0.0
    for p in parts:
        sec = sec * 60 + p
    return sec


def fmt(sec):
    sec = int(round(sec))
    h, r = divmod(sec, 3600)
    m, s = divmod(r, 60)
    return f"{h}:{m:02d}:{s:02d}" if h else f"{m}:{s:02d}"


def probe_duration(path):
    out = subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)],
        capture_output=True, text=True,
    ).stdout.strip()
    try:
        return float(out)
    except ValueError:
        die(f"Dauer nicht lesbar: {path}")


def probe_chapters(path):
    out = subprocess.run(
        ["ffprobe", "-v", "error", "-show_chapters", "-of", "json", str(path)],
        capture_output=True, text=True,
    ).stdout
    try:
        return [
            {"start": float(c["start_time"]), "title": c.get("tags", {}).get("title", "")}
            for c in json.loads(out).get("chapters", [])
        ]
    except (ValueError, KeyError):
        return []


def slugify(text):
    text = unicodedata.normalize("NFKD", text.replace("ß", "ss"))
    text = text.encode("ascii", "ignore").decode()
    text = re.sub(r"[^A-Za-z0-9]+", "-", text).strip("-").lower()
    return text[:60] or "folge"


def load_db():
    return json.loads(DB.read_text()) if DB.exists() else []


def save_db(items):
    LIB.mkdir(parents=True, exist_ok=True)
    DB.write_text(json.dumps(items, ensure_ascii=False, indent=2) + "\n")


def map_chapters(chapters, keeps):
    """Shift source-timeline chapters onto the cut timeline."""
    chapters = sorted(chapters, key=lambda c: c["start"])
    out, offset = [], 0.0
    for a, b in keeps:
        for i, c in enumerate(chapters):
            nxt = chapters[i + 1]["start"] if i + 1 < len(chapters) else float("inf")
            if c["start"] >= b or nxt <= a:
                continue
            start = max(c["start"], a)
            out.append({"start": offset + start - a, "title": c["title"]})
        offset += b - a
    dedup = []
    for c in out:
        if dedup and abs(dedup[-1]["start"] - c["start"]) < 1:
            dedup[-1] = c
        else:
            dedup.append(c)
    return dedup, offset


def cmd_cut(a):
    src = Path(a.src)
    if not src.exists():
        die(f"{src} fehlt")
    dur = probe_duration(src)
    keeps = []
    for k in a.keep or ["0-end"]:
        lo, _, hi = k.partition("-")
        x, y = parse_time(lo or 0, dur), parse_time(hi or "end", dur)
        if not 0 <= x < y <= dur + 1:
            die(f"Bereich {k} ungültig (Dauer {fmt(dur)})")
        keeps.append((x, min(y, dur)))
    keeps.sort()

    if a.chapters:
        raw = json.loads(Path(a.chapters).read_text())
        chapters = [{"start": parse_time(c["start"], dur), "title": c["title"]} for c in raw]
    else:
        chapters = []
    chapters, total = map_chapters(chapters, keeps)

    with tempfile.TemporaryDirectory() as tmp:
        meta = Path(tmp) / "meta.txt"
        lines = [";FFMETADATA1"]
        if a.title:
            lines += [f"title={a.title}", f"album={a.title}"]
        if a.artist:
            lines.append(f"artist={a.artist}")
        lines.append("genre=Podcast")
        for i, c in enumerate(chapters):
            end = chapters[i + 1]["start"] if i + 1 < len(chapters) else total
            t = c["title"].replace("=", "\\=").replace(";", "\\;").replace("#", "\\#")
            lines += ["[CHAPTER]", "TIMEBASE=1/1000",
                      f"START={int(c['start'] * 1000)}", f"END={int(end * 1000)}", f"title={t}"]
        meta.write_text("\n".join(lines) + "\n")

        parts = [f"[0:a]atrim=start={x}:end={y},asetpts=PTS-STARTPTS[s{i}]" for i, (x, y) in enumerate(keeps)]
        joined = "".join(f"[s{i}]" for i in range(len(keeps)))
        graph = ";".join(parts) + f";{joined}concat=n={len(keeps)}:v=0:a=1[out]"

        cmd = ["ffmpeg", "-nostdin", "-loglevel", "error", "-y", "-i", str(src), "-i", str(meta)]
        if a.cover:
            cmd += ["-i", a.cover]
        cmd += ["-filter_complex", graph, "-map", "[out]"]
        if a.cover:
            cmd += ["-map", "2:v", "-c:v", "mjpeg", "-disposition:v", "attached_pic",
                    "-metadata:s:v", "title=Cover"]
        cmd += ["-map_metadata", "1", "-map_chapters", "1",
                "-c:a", "libmp3lame", "-ac", "1", "-b:a", "64k", "-id3v2_version", "3", a.out]
        if subprocess.run(cmd).returncode:
            die("ffmpeg fehlgeschlagen")

    print(f"✓ {a.out} · {fmt(total)} · {len(chapters)} Kapitel")
    for c in chapters:
        print(f"  {fmt(c['start']):>8}  {c['title']}")


def cmd_add(a):
    src = Path(a.mp3)
    if not src.exists():
        die(f"{src} fehlt")
    items = load_db()
    slug = slugify(a.title)
    taken = {i["slug"] for i in items}
    base, n = slug, 2
    while slug in taken:
        slug, n = f"{base}-{n}", n + 1
    EPI.mkdir(parents=True, exist_ok=True)
    dst = EPI / f"{slug}{src.suffix.lower()}"
    shutil.copy2(src, dst)
    chapters = probe_chapters(dst)
    if chapters:
        (EPI / f"{slug}.chapters.json").write_text(json.dumps({
            "version": "1.2.0",
            "chapters": [{"startTime": round(c["start"], 3), "title": c["title"]} for c in chapters],
        }, ensure_ascii=False, indent=2))
    items.append({
        "slug": slug,
        "file": dst.name,
        "title": a.title,
        "desc": a.desc or "",
        "source": a.source or "",
        "added": dt.datetime.now().astimezone().isoformat(timespec="seconds"),
        "duration": round(probe_duration(dst)),
        "size": dst.stat().st_size,
        "chapters": bool(chapters),
    })
    save_db(items)
    print(f"✓ {slug} · {fmt(items[-1]['duration'])} · {len(chapters)} Kapitel")
    sync()


def write_feed(items):
    now = email.utils.format_datetime(dt.datetime.now().astimezone())
    out = [
        '<?xml version="1.0" encoding="UTF-8"?>',
        '<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" '
        'xmlns:podcast="https://podcastindex.org/namespace/1.0">',
        "<channel>",
        f"<title>{escape(FEED_TITLE)}</title>",
        f"<link>{BASE_URL}/</link>",
        "<description>Privat. Ausschnitte zum Nachhören.</description>",
        "<language>de</language>",
        f"<lastBuildDate>{now}</lastBuildDate>",
        "<itunes:block>Yes</itunes:block>",
    ]
    if (PUB / "cover.jpg").exists():
        out.append(f'<itunes:image href="{BASE_URL}/cover.jpg"/>')
    for i in sorted(items, key=lambda x: x["added"], reverse=True):
        url = f"{BASE_URL}/episodes/{i['file']}"
        desc = i["desc"] + (f"\n\nQuelle: {i['source']}" if i["source"] else "")
        pub = email.utils.format_datetime(dt.datetime.fromisoformat(i["added"]))
        out += [
            "<item>",
            f"<title>{escape(i['title'])}</title>",
            f"<guid isPermaLink=\"false\">{escape(i['slug'])}</guid>",
            f"<pubDate>{pub}</pubDate>",
            f"<description>{escape(desc.strip())}</description>",
            f'<enclosure url="{escape(url)}" length="{i["size"]}" type="audio/mpeg"/>',
            f"<itunes:duration>{i['duration']}</itunes:duration>",
        ]
        if i.get("chapters"):
            out.append(f'<podcast:chapters url="{BASE_URL}/episodes/{i["slug"]}.chapters.json" '
                       'type="application/json+chapters"/>')
        out.append("</item>")
    out += ["</channel>", "</rss>"]
    PUB.mkdir(parents=True, exist_ok=True)
    (PUB / "feed.xml").write_text("\n".join(out) + "\n")


def wrangler(*args):
    r = subprocess.run(["npx", "--yes", "wrangler", "r2", "object", *args, "--remote"],
                       capture_output=True, text=True)
    if r.returncode:
        print(r.stdout[-800:] + r.stderr[-800:], file=sys.stderr)
    return r.returncode == 0


def sync():
    if not BASE_URL:
        die(f"base_url fehlt in {CONFIG_FILE}")
    write_feed(load_db())
    if UPLOAD == "none":
        print(f"✓ Feed geschrieben: {PUB}/feed.xml (kein Upload eingestellt)")
        return
    if UPLOAD == "command":
        cmd = CONFIG.get("command", "").replace("{public}", str(PUB))
        if not cmd or subprocess.run(cmd, shell=True).returncode:
            die("Upload-Befehl fehlgeschlagen – lokal ist alles aktuell, später `pod sync`")
        print(f"✓ Feed synchron: {BASE_URL}/feed.xml")
        return
    remote = json.loads(REMOTE_STATE.read_text()) if REMOTE_STATE.exists() else {}
    local = {}
    for f in sorted(PUB.rglob("*")):
        if f.is_file():
            st = f.stat()
            local[f.relative_to(PUB).as_posix()] = f"{st.st_size}:{int(st.st_mtime)}"

    ok = True
    for key in [k for k in local if k != "feed.xml"] + ["feed.xml"]:
        if remote.get(key) == local[key]:
            continue
        ctype = CONTENT_TYPES.get(Path(key).suffix.lower(), "application/octet-stream")
        print(f"↑ {key}")
        if wrangler("put", f"{BUCKET}/{key}", "--file", str(PUB / key), "--content-type", ctype):
            remote[key] = local[key]
        else:
            ok = False
    for key in [k for k in remote if k not in local]:
        print(f"✗ {key}")
        if wrangler("delete", f"{BUCKET}/{key}"):
            remote.pop(key)
        else:
            ok = False

    REMOTE_STATE.write_text(json.dumps(remote, indent=2) + "\n")
    if not ok:
        die("Upload nach Cloudflare R2 unvollständig – lokal ist alles aktuell, später `pod sync`")
    print(f"✓ Feed synchron: {BASE_URL}/feed.xml")


def age_days(i):
    return (dt.datetime.now().astimezone() - dt.datetime.fromisoformat(i["added"])).days


def show(items):
    if not items:
        print("(keine Folgen)")
        return
    for i in sorted(items, key=lambda x: x["added"]):
        print(f"{i['slug']:<45} {i['added'][:10]}  {age_days(i):>3} Tage  {fmt(i['duration']):>8}  {i['title']}")


def cmd_list(a):
    show(load_db())


def cmd_old(a):
    show([i for i in load_db() if age_days(i) >= a.days])


def cmd_rm(a):
    items = load_db()
    known = {i["slug"] for i in items}
    missing = [s for s in a.slugs if s not in known]
    if missing:
        die(f"unbekannt: {', '.join(missing)}")
    for i in items:
        if i["slug"] in a.slugs:
            for f in EPI.glob(f"{i['slug']}.*"):
                f.unlink()
            print(f"✗ {i['slug']}")
    save_db([i for i in items if i["slug"] not in a.slugs])
    sync()


def main():
    p = argparse.ArgumentParser(prog="pod", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = p.add_subparsers(dest="cmd", required=True)

    c = sub.add_parser("cut")
    c.add_argument("src")
    c.add_argument("out")
    c.add_argument("--keep", action="append")
    c.add_argument("--chapters")
    c.add_argument("--title")
    c.add_argument("--artist")
    c.add_argument("--cover")
    c.set_defaults(fn=cmd_cut)

    c = sub.add_parser("add")
    c.add_argument("mp3")
    c.add_argument("--title", required=True)
    c.add_argument("--desc")
    c.add_argument("--source")
    c.set_defaults(fn=cmd_add)

    sub.add_parser("list").set_defaults(fn=cmd_list)

    c = sub.add_parser("old")
    c.add_argument("--days", type=int, default=28)
    c.set_defaults(fn=cmd_old)

    c = sub.add_parser("rm")
    c.add_argument("slugs", nargs="+")
    c.set_defaults(fn=cmd_rm)

    sub.add_parser("sync").set_defaults(fn=lambda a: sync())

    a = p.parse_args()
    a.fn(a)


if __name__ == "__main__":
    main()
