#!/usr/bin/env python3
"""Content Calendar CLI — RoyalStylesCreations
Manage and track content across Etsy, Pinterest, Instagram, Facebook.
"""

import argparse
import json
import os
import sys
import uuid
from datetime import datetime, timedelta, date
from pathlib import Path

DATA_DIR = Path.home() / ".openclaw/workspace/data/content-calendar"
CALENDAR_FILE = DATA_DIR / "calendar.json"
IDEAS_FILE = DATA_DIR / "ideas.json"
PUBLISHED_FILE = DATA_DIR / "published.json"

PLATFORMS = ["pinterest", "instagram", "facebook", "etsy"]
NICHES = ["usmc", "military", "patriotic", "christian", "nature", "seasonal", "general"]


def ensure_data_dir():
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    for f in [CALENDAR_FILE, IDEAS_FILE, PUBLISHED_FILE]:
        if not f.exists():
            f.write_text("[]")


def load(path):
    try:
        return json.loads(path.read_text())
    except (json.JSONDecodeError, FileNotFoundError):
        return []


def save(path, data):
    path.write_text(json.dumps(data, indent=2, default=str))


def make_id():
    return str(uuid.uuid4())[:8]


def cmd_add(args):
    ensure_data_dir()
    calendar = load(CALENDAR_FILE)

    # Resolve date
    if args.date:
        try:
            scheduled = datetime.strptime(args.date, "%Y-%m-%d").date().isoformat()
        except ValueError:
            print(f"ERROR: Invalid date format '{args.date}'. Use YYYY-MM-DD")
            sys.exit(1)
    else:
        scheduled = (date.today() + timedelta(days=1)).isoformat()

    entry = {
        "id": make_id(),
        "title": args.title,
        "platforms": args.platforms or ["instagram"],
        "niche": args.niche or "general",
        "date": scheduled,
        "status": "scheduled",
        "notes": args.notes or "",
        "created": datetime.now().isoformat()[:19],
    }
    calendar.append(entry)
    save(CALENDAR_FILE, calendar)
    print(f"✅ Added: [{entry['id']}] {entry['title']} → {entry['date']} | {', '.join(entry['platforms'])}")


def cmd_week(args):
    ensure_data_dir()
    calendar = load(CALENDAR_FILE)
    today = date.today()
    week_end = today + timedelta(days=7)

    items = [
        e for e in calendar
        if today.isoformat() <= e.get("date", "") <= week_end.isoformat()
        and e.get("status") != "published"
    ]
    items.sort(key=lambda x: x["date"])

    if not items:
        print("No scheduled content for the next 7 days.")
        return

    print(f"\n📅  Content Calendar — {today.isoformat()} to {week_end.isoformat()}\n")
    current_day = None
    for e in items:
        if e["date"] != current_day:
            current_day = e["date"]
            day_name = datetime.strptime(current_day, "%Y-%m-%d").strftime("%A, %b %-d")
            print(f"  ── {day_name} ──")
        platforms = ", ".join(e.get("platforms", []))
        niche = e.get("niche", "")
        print(f"     [{e['id']}] {e['title']}")
        print(f"            {platforms} | #{niche}")
        if e.get("notes"):
            print(f"            📝 {e['notes']}")
    print()


def cmd_list(args):
    ensure_data_dir()
    calendar = load(CALENDAR_FILE)

    items = calendar
    if args.platform:
        items = [e for e in items if args.platform in e.get("platforms", [])]
    if args.niche:
        items = [e for e in items if e.get("niche") == args.niche]
    if args.status:
        items = [e for e in items if e.get("status") == args.status]

    items = [e for e in items if e.get("status") != "published"]
    items.sort(key=lambda x: x.get("date", ""))

    if not items:
        print("No matching entries.")
        return

    print(f"\n{'ID':10} {'Date':12} {'Platforms':25} {'Niche':12} Title")
    print("-" * 80)
    for e in items:
        platforms = ",".join(e.get("platforms", []))
        print(f"  {e['id']:8} {e.get('date','N/A'):12} {platforms:25} {e.get('niche',''):12} {e['title']}")
    print()


def cmd_publish(args):
    ensure_data_dir()
    calendar = load(CALENDAR_FILE)
    published = load(PUBLISHED_FILE)

    entry = next((e for e in calendar if e["id"] == args.id), None)
    if not entry:
        print(f"ERROR: ID '{args.id}' not found.")
        sys.exit(1)

    entry["status"] = "published"
    entry["publishedAt"] = datetime.now().isoformat()[:19]
    published.append(entry)
    calendar = [e for e in calendar if e["id"] != args.id]

    save(CALENDAR_FILE, calendar)
    save(PUBLISHED_FILE, published)
    print(f"✅ Marked published: [{entry['id']}] {entry['title']}")


def cmd_idea(args):
    ensure_data_dir()
    ideas = load(IDEAS_FILE)
    entry = {
        "id": make_id(),
        "title": args.title,
        "niche": args.niche or "general",
        "notes": args.notes or "",
        "addedDate": date.today().isoformat(),
    }
    ideas.append(entry)
    save(IDEAS_FILE, ideas)
    print(f"💡 Idea saved: [{entry['id']}] {entry['title']}")


def cmd_export_publer(args):
    ensure_data_dir()
    calendar = load(CALENDAR_FILE)
    today = date.today()
    end = today + timedelta(days=args.days or 7)

    items = [
        e for e in calendar
        if today.isoformat() <= e.get("date", "") <= end.isoformat()
        and e.get("status") == "scheduled"
    ]

    import csv
    out = args.output or "/tmp/publer-import.csv"
    with open(out, "w", newline="") as f:
        writer = csv.writer(f)
        # Publer CSV format: Date, Time, Message, Link, Image
        writer.writerow(["Date", "Time", "Message", "Link", "Image"])
        for e in sorted(items, key=lambda x: x["date"]):
            for platform in e.get("platforms", ["instagram"]):
                writer.writerow([
                    e["date"],
                    "09:00",
                    e["title"],
                    "",
                    "",
                ])
    print(f"📤 Publer CSV exported: {out} ({len(items)} items)")


def cmd_stats(args):
    ensure_data_dir()
    published = load(PUBLISHED_FILE)
    calendar = load(CALENDAR_FILE)

    month = args.month or date.today().strftime("%Y-%m")
    pub = [e for e in published if e.get("publishedAt", "").startswith(month)]
    sched = [e for e in calendar if e.get("date", "").startswith(month)]

    print(f"\n📊 Content Stats — {month}\n")
    print(f"  Published:  {len(pub)}")
    print(f"  Scheduled:  {len(sched)}")

    if pub:
        by_platform = {}
        for e in pub:
            for p in e.get("platforms", []):
                by_platform[p] = by_platform.get(p, 0) + 1
        print("\n  Published by platform:")
        for p, c in sorted(by_platform.items(), key=lambda x: -x[1]):
            print(f"    {p:20s} {c}")

    print()


def main():
    parser = argparse.ArgumentParser(description="Content Calendar CLI")
    sub = parser.add_subparsers(dest="cmd")

    # add
    p_add = sub.add_parser("add", help="Add scheduled content")
    p_add.add_argument("--title", required=True)
    p_add.add_argument("--platforms", nargs="+", choices=PLATFORMS)
    p_add.add_argument("--niche", choices=NICHES)
    p_add.add_argument("--date", help="YYYY-MM-DD")
    p_add.add_argument("--notes")

    # week
    sub.add_parser("week", help="Show this week's schedule")

    # list
    p_list = sub.add_parser("list", help="List all scheduled content")
    p_list.add_argument("--platform")
    p_list.add_argument("--niche")
    p_list.add_argument("--status")

    # publish
    p_pub = sub.add_parser("publish", help="Mark content as published")
    p_pub.add_argument("--id", required=True)

    # idea
    p_idea = sub.add_parser("idea", help="Add an idea to backlog")
    p_idea.add_argument("--title", required=True)
    p_idea.add_argument("--niche", choices=NICHES)
    p_idea.add_argument("--notes")

    # export-publer
    p_ep = sub.add_parser("export-publer", help="Export to Publer CSV")
    p_ep.add_argument("--days", type=int, default=7)
    p_ep.add_argument("--output")

    # stats
    p_stats = sub.add_parser("stats", help="Monthly stats")
    p_stats.add_argument("--month", help="YYYY-MM (default: current month)")

    args = parser.parse_args()

    dispatch = {
        "add": cmd_add,
        "week": cmd_week,
        "list": cmd_list,
        "publish": cmd_publish,
        "idea": cmd_idea,
        "export-publer": cmd_export_publer,
        "stats": cmd_stats,
    }

    if args.cmd in dispatch:
        dispatch[args.cmd](args)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
