"""Instagram post preflight - checks a planned Instagram API post before you create
any media container. MIT License - APIWings (https://apiwings.com/blog/instagram-api-post)

It works on metadata you already have (format, bytes, width, height, duration...),
so it never downloads or opens a file. Rules come from instagram-publishing-rules.json.
Standard library only. Same results as instagram-post-preflight.mjs.

Usage:
    python instagram_post_preflight.py example-posts.json
    from instagram_post_preflight import check_post
"""

import json
import math
import re
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
RULES = json.loads((HERE / "instagram-publishing-rules.json").read_text(encoding="utf-8"))

HASHTAG = re.compile(r"#\w+")
MENTION = re.compile(r"@[A-Za-z0-9._]+")


def _round(x, digits=3):
    f = 10 ** digits
    return math.floor(x * f + 0.5) / f  # same as JavaScript Math.round for positive numbers


def _num(x):
    """Print numbers the way JavaScript does (2.0 -> "2")."""
    if isinstance(x, float) and x.is_integer():
        return str(int(x))
    return str(x)


def _add(out, level, code, message):
    out.append({"level": level, "code": code, "message": message})


def _check_caption(post, out):
    r = RULES["caption"]
    caption = post.get("caption") or ""
    if not caption:
        return
    chars = len(caption)
    if chars > r["max_chars"]:
        _add(out, "error", "caption_too_long", f"Caption has {chars} characters; the maximum is {r['max_chars']}.")
    hashtags = len(HASHTAG.findall(caption))
    if hashtags > r["max_hashtags"]:
        _add(out, "error", "too_many_hashtags", f"Caption has {hashtags} hashtags; the maximum is {r['max_hashtags']}.")
    mentions = len(MENTION.findall(caption))
    if mentions > r["max_mentions"]:
        _add(out, "error", "too_many_mentions", f"Caption has {mentions} @mentions; the maximum is {r['max_mentions']}.")


def _check_collaborators(post, out):
    lst = post.get("collaborators") or []
    if not lst:
        return
    if post.get("type") == "STORIES":
        _add(out, "error", "collaborators_not_supported", "Stories cannot have collaborators.")
        return
    mx = RULES["collaborators"]["max"]
    if len(lst) > mx:
        _add(out, "error", "too_many_collaborators", f"{len(lst)} collaborators; the maximum is {mx}.")


def _check_alt_text(item, where, alt_allowed, out):
    alt = item.get("alt_text") or ""
    if not alt:
        return
    if not alt_allowed:
        _add(out, "error", "alt_text_not_supported", f"{where}: alt text is only supported on feed and carousel images.")
        return
    n = len(alt)
    mx = RULES["alt_text"]["max_chars"]
    if n > mx:
        _add(out, "error", "alt_text_too_long", f"{where}: alt text has {n} characters; the maximum is {mx}.")


def _check_feed_image(item, where, out):
    r = RULES["feed_image"]
    if str(item.get("format")).lower() not in r["formats"]:
        _add(out, "error", "image_format", f"{where}: {item.get('format')} is not supported; Instagram accepts JPEG only.")
    if item["bytes"] > r["max_bytes"]:
        _add(out, "error", "image_too_large", f"{where}: {_num(item['bytes'])} bytes; the maximum is {r['max_bytes']}.")
    aspect = item["width"] / item["height"]
    if aspect < r["min_aspect"] or aspect > r["max_aspect"]:
        _add(out, "error", "image_aspect", f"{where}: aspect ratio {_num(_round(aspect))} is outside 4:5 (0.8) to 1.91:1.")
    if item["width"] < r["min_width"] or item["width"] > r["max_width"]:
        _add(out, "warning", "image_width_scaled",
             f"{where}: width {_num(item['width'])} px is outside {r['min_width']}-{r['max_width']} px; Instagram will scale it.")
    cs = item.get("color_space")
    if cs and str(cs).lower() != r["color_space"]:
        _add(out, "warning", "image_color_space", f"{where}: {cs} will be converted to sRGB.")


def _check_story_image(item, where, out):
    r = RULES["story_image"]
    if str(item.get("format")).lower() not in r["formats"]:
        _add(out, "error", "image_format", f"{where}: {item.get('format')} is not supported; Instagram accepts JPEG only.")
    if item["bytes"] > r["max_bytes"]:
        _add(out, "error", "image_too_large", f"{where}: {_num(item['bytes'])} bytes; the maximum is {r['max_bytes']}.")


def _check_encoding(item, where, out):
    r = RULES["video_encoding"]
    if str(item.get("container")).lower() not in r["containers"]:
        _add(out, "error", "video_container", f"{where}: {item.get('container')} is not supported; use MP4 or MOV.")
    if str(item.get("video_codec")).lower() not in r["video_codecs"]:
        _add(out, "error", "video_codec", f"{where}: {item.get('video_codec')} is not supported; use H.264 or HEVC.")
    if item["fps"] < r["min_fps"] or item["fps"] > r["max_fps"]:
        _add(out, "error", "video_fps", f"{where}: {_num(item['fps'])} fps is outside {r['min_fps']}-{r['max_fps']} fps.")
    if item["width"] > r["max_width"]:
        _add(out, "error", "video_width", f"{where}: {_num(item['width'])} px wide; the maximum is {r['max_width']}.")
    if item["bitrate_mbps"] > r["max_bitrate_mbps"]:
        _add(out, "error", "video_bitrate", f"{where}: {_num(item['bitrate_mbps'])} Mbps; the maximum is {r['max_bitrate_mbps']}.")
    if item.get("audio_codec"):
        if str(item["audio_codec"]).lower() not in r["audio_codecs"]:
            _add(out, "error", "audio_codec", f"{where}: {item['audio_codec']} audio is not supported; use AAC.")
        if item["audio_hz"] > r["max_audio_hz"]:
            _add(out, "error", "audio_sample_rate", f"{where}: {_num(item['audio_hz'])} Hz; the maximum is {r['max_audio_hz']}.")
        if item["audio_channels"] > r["max_audio_channels"]:
            _add(out, "error", "audio_channels", f"{where}: {_num(item['audio_channels'])} audio channels; use mono or stereo.")


def _check_video_limits(item, where, r, out, warn_not_916):
    if item["duration_s"] < r["min_seconds"]:
        _add(out, "error", "video_too_short", f"{where}: {_num(item['duration_s'])} s; the minimum is {r['min_seconds']} s.")
    if item["duration_s"] > r["max_seconds"]:
        _add(out, "error", "video_too_long", f"{where}: {_num(item['duration_s'])} s; the maximum is {r['max_seconds']} s.")
    if item["bytes"] > r["max_bytes"]:
        _add(out, "error", "video_too_large", f"{where}: {_num(item['bytes'])} bytes; the maximum is {r['max_bytes']}.")
    aspect = item["width"] / item["height"]
    if aspect < r["min_aspect"] or aspect > r["max_aspect"]:
        _add(out, "error", "video_aspect",
             f"{where}: aspect ratio {_num(_round(aspect))} is outside {_num(r['min_aspect'])}:1 to {_num(r['max_aspect'])}:1.")
    elif warn_not_916 and abs(aspect - r["recommended_aspect"]) > 0.01:
        _add(out, "warning", "video_not_9_16", f"{where}: aspect ratio {_num(_round(aspect))}; Meta recommends 9:16 for Reels.")


def check_post(post):
    out = []
    media = post.get("media") or []
    ptype = post.get("type")
    if ptype not in RULES["post_types"]:
        _add(out, "error", "unknown_type", f"Unknown post type {ptype}; use IMAGE, REELS, STORIES or CAROUSEL.")
        return _finish(post, out)

    if ptype == "IMAGE":
        if len(media) != 1 or media[0].get("kind") != "image":
            _add(out, "error", "media_count", "An IMAGE post needs exactly one image.")
        else:
            _check_feed_image(media[0], "image", out)
            _check_alt_text(media[0], "image", True, out)
    elif ptype == "REELS":
        if len(media) != 1 or media[0].get("kind") != "video":
            _add(out, "error", "media_count", "A Reel needs exactly one video.")
        else:
            _check_encoding(media[0], "video", out)
            _check_video_limits(media[0], "video", RULES["reel"], out, True)
            _check_alt_text(media[0], "video", False, out)
    elif ptype == "STORIES":
        if len(media) != 1:
            _add(out, "error", "media_count", "A story needs exactly one image or video.")
        elif media[0].get("kind") == "image":
            _check_story_image(media[0], "image", out)
            _check_alt_text(media[0], "image", False, out)
        else:
            _check_encoding(media[0], "video", out)
            _check_video_limits(media[0], "video", RULES["story_video"], out, False)
            _check_alt_text(media[0], "video", False, out)
    elif ptype == "CAROUSEL":
        r = RULES["carousel"]
        n = len(media)
        if n < r["min_items"]:
            _add(out, "error", "carousel_too_few", f"A carousel needs at least {r['min_items']} items; it has {n}.")
        elif n > r["max_items"]:
            _add(out, "error", "carousel_too_many", f"A carousel allows up to {r['max_items']} items; it has {n}.")
        elif n > r["safe_max_items"]:
            _add(out, "warning", "carousel_over_10",
                 f"{n} items: the reference allows {r['max_items']}, but error 2207028 still says 10. Test with your app first.")
        first_aspect = None
        mixed = False
        has_video = False
        for i, item in enumerate(media):
            where = f"item {i + 1}"
            if item.get("kind") == "image":
                _check_feed_image(item, where, out)
                _check_alt_text(item, where, True, out)
                aspect = _round(item["width"] / item["height"])
                if first_aspect is None:
                    first_aspect = aspect
                elif aspect != first_aspect:
                    mixed = True
            else:
                has_video = True
                _check_encoding(item, where, out)
                _check_alt_text(item, where, False, out)
        if mixed:
            _add(out, "warning", "carousel_cropped",
                 "Images have different aspect ratios; Instagram crops them all to the first image's ratio.")
        if has_video:
            _add(out, "warning", "carousel_video_unspecified",
                 "Meta publishes no size or duration limits for carousel videos; only encoding was checked.")

    _check_caption(post, out)
    _check_collaborators(post, out)
    return _finish(post, out)


def _finish(post, out):
    errors = sum(1 for c in out if c["level"] == "error")
    return {"id": post.get("id"), "ready": errors == 0, "errors": errors, "warnings": len(out) - errors, "checks": out}


if __name__ == "__main__":
    path = Path(sys.argv[1]) if len(sys.argv) > 1 else HERE / "example-posts.json"
    for post in json.loads(path.read_text(encoding="utf-8"))["posts"]:
        r = check_post(post)
        state = "READY" if r["ready"] else "BLOCKED"
        plural = lambda n, w: f"{n} {w}{'' if n == 1 else 's'}"
        print(f"{r['id']}: {state} ({plural(r['errors'], 'error')}, {plural(r['warnings'], 'warning')})")
        for c in r["checks"]:
            print(f"  {c['level']:<7} {c['code']}: {c['message']}")
