"""Social media schedule planner (Python 3.9+, no dependencies).

Turns one "publish at this local time" request into a per-network plan:
the exact UTC instant, whether the network can schedule natively, what to
prepare and when, and the problems you would otherwise find at publish time
(daylight saving changes, local times that do not exist, tokens that expire
before the post goes out).

Rules come from each network's official documentation, checked in
November 2026. Sources: social-media-scheduling-rules.json.
Published by APIWings (https://apiwings.com/blog/social-media-scheduling-api). MIT licence.
"""
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

MIN = timedelta(minutes=1)
DAY = timedelta(days=1)

# How far ahead each network lets you hand over a scheduled post (native scheduling).
# Facebook: the Pages API guide says 30 days, the Page feed reference 75; we use the stricter 30.
NATIVE = {
    "facebook": {"min": 10 * MIN, "max": 30 * DAY,
                 "how": "POST /{page-id}/feed with published=false and scheduled_publish_time"},
    "youtube": {"min": None, "max": None,
                "how": "upload now: videos.insert with privacyStatus=private and publishAt (100 uploads a day by default)"},
}

# Steps for networks without native scheduling: what your own queue does, relative to publish time.
QUEUE = {
    "instagram": [(-10 * MIN, "create the media container (it expires if not published within 24 hours)"),
                  (-9 * MIN, "check status_code once a minute until FINISHED (max 5 minutes)"),
                  (-1 * MIN, "check content_publishing_limit (100 API posts per 24 hours)"),
                  (0 * MIN, "POST /{ig-id}/media_publish with creation_id")],
    "threads": [(-10 * MIN, "create the Threads media container"),
                (-9 * MIN, "wait at least 30 seconds, then check status until FINISHED"),
                (0 * MIN, "POST /{threads-user-id}/threads_publish with creation_id")],
    "linkedin": [(-10 * MIN, "upload images or video and keep their URNs"),
                 (0 * MIN, "POST /rest/posts with lifecycleState=PUBLISHED")],
    "tiktok": [(-10 * MIN, "refresh the access token (it lasts 2 hours) and query creator_info"),
               (-9 * MIN, "check the stored privacy_level is still in privacy_level_options"),
               (0 * MIN, "POST /v2/post/publish/video/init/ (or content/init for photos)")],
    "x": [(-5 * MIN, "refresh the access token if needed (it lasts 2 hours)"),
          (0 * MIN, "POST /2/tweets")],
    "bluesky": [(-5 * MIN, "refresh the session if needed and upload images (blobs)"),
                (0 * MIN, "com.atproto.repo.createRecord with createdAt set to the current time")],
}

NETWORKS = ["facebook", "youtube", "instagram", "threads", "linkedin", "tiktok", "x", "bluesky"]


def iso(dt):
    return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def offset_str(td):
    minutes = int(td.total_seconds() // 60)
    sign = "+" if minutes >= 0 else "-"
    minutes = abs(minutes)
    return f"{sign}{minutes // 60:02d}:{minutes % 60:02d}"


def fmt_hours(td):
    minutes = abs(int(td.total_seconds() // 60))
    if minutes == 60:
        return "one hour"
    return f"{minutes // 60} h {minutes % 60:02d} min" if minutes % 60 else f"{minutes // 60} hours"


def resolve_local(local, tz_name):
    """Local wall time + IANA zone -> (UTC datetime, offset, warnings). Raises on a time that does not exist."""
    tz = ZoneInfo(tz_name)
    naive = datetime.fromisoformat(local)
    if naive.tzinfo is not None:
        raise ValueError("publish_at_local must not include an offset: send the wall time and the time zone")
    first, second = naive.replace(tzinfo=tz, fold=0), naive.replace(tzinfo=tz, fold=1)
    warnings = []
    # A wall time that does not survive a round trip through UTC does not exist (clocks jumped forward).
    if first.astimezone(timezone.utc).astimezone(tz).replace(tzinfo=None) != naive:
        raise ValueError(f"{local} does not exist in {tz_name}: the clocks jump forward past it. Pick another time.")
    if first.utcoffset() != second.utcoffset():
        warnings.append({"code": "ambiguous_local_time",
                         "message": f"{local} happens twice in {tz_name} (clocks go back); using the first one, "
                                    f"{offset_str(first.utcoffset())}."})
    return first.astimezone(timezone.utc), first.utcoffset(), warnings


def plan(request, now=None):
    now = now or datetime.now(timezone.utc)
    if isinstance(now, str):
        now = datetime.fromisoformat(now.replace("Z", "+00:00"))
    tz_name = request["time_zone"]
    publish_utc, offset, warnings = resolve_local(request["publish_at_local"], tz_name)
    offset_now = now.astimezone(ZoneInfo(tz_name)).utcoffset()
    if offset_now != offset:
        warnings.append({"code": "offset_changes_before_publish",
                         "message": f"{tz_name} is {offset_str(offset_now)} today but {offset_str(offset)} at publish "
                                    f"time. Store the time zone, not today's offset, or the post goes out "
                                    f"{fmt_hours(offset - offset_now)} off."})
    if publish_utc <= now:
        warnings.append({"code": "publish_time_in_past", "message": "The publish time has passed: it would go out now."})

    result = {"publish_at_utc": iso(publish_utc), "utc_offset_at_publish": offset_str(offset),
              "warnings": warnings, "networks": {}}
    tokens = request.get("connection_valid_until", {})
    for net in request["networks"]:
        if net not in NETWORKS:
            raise ValueError(f"unknown network: {net}")
        entry = {"mode": "", "steps": [], "problems": []}
        lead = publish_utc - now
        if net in NATIVE:
            rule = NATIVE[net]
            if rule["max"] is not None and lead > rule["max"]:
                handover = publish_utc - rule["max"] + DAY  # one day inside the window
                entry["mode"] = "native_later"
                entry["steps"].append({"at": iso(handover), "action": rule["how"]})
                entry["problems"].append(f"more than {rule['max'].days} days ahead: keep it in your own queue "
                                         f"and hand it over on {iso(handover)}")
            elif rule["min"] is not None and lead < rule["min"]:
                entry["mode"] = "your_queue"
                entry["steps"].append({"at": iso(publish_utc), "action": "publish with published=true"})
                entry["problems"].append("less than 10 minutes ahead: too soon for native scheduling")
            else:
                entry["mode"] = "native"
                entry["steps"].append({"at": iso(now), "action": rule["how"]})
        else:
            entry["mode"] = "your_queue"
            for delta, action in QUEUE[net]:
                entry["steps"].append({"at": iso(publish_utc + delta), "action": action})
        valid_until = tokens.get(net)
        if valid_until:
            vu = datetime.fromisoformat(valid_until.replace("Z", "+00:00"))
            # The token is needed at the first step that calls the network.
            needed_until = max(datetime.fromisoformat(s["at"].replace("Z", "+00:00")) for s in entry["steps"])
            if vu < needed_until:
                entry["problems"].append(f"connection expires {iso(vu)}, before {iso(needed_until)}: "
                                         f"ask the user to reconnect first")
            elif vu - needed_until < 7 * DAY:
                entry["problems"].append(f"connection expires {iso(vu)}, less than 7 days after it is needed")
        result["networks"][net] = entry
    return result


if __name__ == "__main__":
    import json
    import sys
    data = json.load(open(sys.argv[1] if len(sys.argv) > 1 else "example-schedule.json", encoding="utf-8"))
    print(json.dumps(plan(data["request"], data.get("now")), indent=2))
