#!/usr/bin/env python3
"""CLI entrypoint for the content-generation pipeline.

Usage:
  python bin/run_pipeline.py
  python bin/run_pipeline.py --dry-run
  python bin/run_pipeline.py --demo          # no Claude / Drive / Telegram
  DRY_RUN=true python bin/run_pipeline.py
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from datetime import datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))


def run_demo(batch_size: int = 3) -> dict:
    """Local smoke-test: asset rendering + ffmpeg only (no external APIs)."""
    from src.generators.assets import AssetProducer
    from src.generators.visuals import VisualRenderer
    from src.services.ideation import ContentIdea, PlatformPost
    from src.util.text import slugify

    out_root = ROOT / "storage" / "runs"
    ts = datetime.now().strftime("%Y%m%d_%H%M%S")
    batch_dir = out_root / f"batch_demo_{ts}"
    batch_dir.mkdir(parents=True, exist_ok=True)

    def _plat(post: str) -> dict[str, PlatformPost]:
        return {
            "linkedin": PlatformPost(post=post, hashtags=["AI", "TechNews"]),
            "instagram": PlatformPost(post=post, hashtags=["AI", "TechTok", "StartupLife"]),
            "x": PlatformPost(post=post[:260], hashtags=["AI"]),
            "threads": PlatformPost(post=post, hashtags=["Tech", "AI"]),
            "facebook": PlatformPost(post=post, hashtags=["AI", "Technology"]),
        }

    samples = [
        ContentIdea(
            id="idea-01",
            format="image",
            topic="OpenAI GPT-5.6 rollout",
            hook="GPT-5.6 just dropped 👀",
            news_url="https://openai.com/blog",
            news_title="GPT-5.6 is now the preferred model in Microsoft 365 Copilot",
            visual_brief="Bold tech visual about AI model release.",
            creative_direction="Neon cyber corridor meeting polished enterprise glass.",
            layout="neon_tech",
            palette=["#070B14", "#5B8CFF", "#00F5D4"],
            why_it_matters="Default AI inside Microsoft 365 just leveled up overnight.",
            key_fact="GPT-5.6 is now the preferred Copilot model.",
            platforms=_plat("OpenAI just pushed GPT-5.6 into Copilot — and the timeline for enterprises just compressed.\n\nWould you trust it on production docs yet? 👇"),
        ),
        ContentIdea(
            id="idea-02",
            format="carousel",
            topic="Startup funding week",
            hook="$100M for AI infra 🚀",
            news_url="https://techcrunch.com",
            news_title="Railway secures $100 million",
            visual_brief="Funding story carousel.",
            creative_direction="David vs Goliath cloud war — electric blues vs steel greys.",
            layout="bold_stat",
            palette=["#0B1020", "#FF6B35", "#F8FAFC"],
            slides=[
                {"title": "The raise", "body": "Railway just pulled $100M to take on legacy cloud."},
                {"title": "Why now", "body": "AI workloads need simpler deploy paths."},
                {"title": "For builders", "body": "Less YAML. More shipping."},
                {"title": "Hot take", "body": "Infra is the new moat."},
                {"title": "CTA", "body": "Save this — who would you bet on next?"},
            ],
            platforms=_plat("Another massive AI infra bet just landed.\n\nRailway → $100M. The cloud wars aren't slowing down."),
        ),
        ContentIdea(
            id="idea-03",
            format="video",
            topic="Cyber breach alert",
            hook="Patch this NOW",
            news_url="https://thehackernews.com",
            news_title="Critical vulnerability patched",
            visual_brief="Urgent cyber short.",
            creative_direction="Red-alert SOC room with kinetic type.",
            layout="split_diagonal",
            palette=["#12050A", "#FF2E63", "#FFFFFF"],
            video_style="glitch",
            video_script=[
                {"on_screen": "Critical CVE dropped", "voiceover": "Security teams — this one's urgent.", "visual": ""},
                {"on_screen": "Patch window shrinking", "voiceover": "Update before attackers automate it.", "visual": ""},
                {"on_screen": "Follow for cyber alerts", "voiceover": "Drop a lock if you want more breakdowns.", "visual": ""},
            ],
            platforms=_plat("New critical vuln in the wild — patch window is shrinking.\n\nAre your systems updated?"),
        ),
    ][:batch_size]

    renderer = VisualRenderer("Synapse", "#0B1020", "#5B8CFF", "#070B14", ROOT / "data" / "fonts")
    producer = AssetProducer(renderer, enable_video=True, video_max_seconds=12, enable_ai_images=False)
    ideas_meta = []
    for idea in samples:
        folder = batch_dir / f"{idea.id}_{slugify(idea.topic)}"
        ideas_meta.append(producer.produce(idea, folder))

    manifest = {"batch_id": f"demo_{ts}", "ideas": ideas_meta, "demo": True}
    (batch_dir / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
    return manifest


def main() -> int:
    parser = argparse.ArgumentParser(description="Automated social content pipeline")
    parser.add_argument("--dry-run", action="store_true", help="Skip Drive upload and Telegram")
    parser.add_argument("--demo", action="store_true", help="Render sample assets without Claude/Drive/Telegram")
    parser.add_argument("--batch-size", type=int, default=None, help="Override BATCH_SIZE")
    args = parser.parse_args()

    if args.demo:
        manifest = run_demo(batch_size=args.batch_size or 3)
        print(json.dumps({"ok": True, "batch_id": manifest["batch_id"], "items": len(manifest["ideas"]), "mode": "demo"}, indent=2))
        return 0

    if args.dry_run:
        os.environ["DRY_RUN"] = "true"
    if args.batch_size is not None:
        os.environ["BATCH_SIZE"] = str(args.batch_size)

    from src.config import load_settings
    from src.pipeline import ContentPipeline

    settings = load_settings()
    settings.output_dir.mkdir(parents=True, exist_ok=True)
    settings.storage_tmp.mkdir(parents=True, exist_ok=True)
    settings.storage_logs.mkdir(parents=True, exist_ok=True)

    manifest = ContentPipeline(settings).run()
    print(json.dumps({"ok": True, "batch_id": manifest["batch_id"], "items": len(manifest.get("ideas", []))}, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
