#!/usr/bin/env python3
"""Upload an image, create an article, then update it.

Uses only the Python standard library.

Environment:
  PRACTICAL_AI_BASE_URL   default http://127.0.0.1:3847
  PUBLISH_API_TOKEN       required
"""

import json
import os
import struct
import sys
import urllib.error
import urllib.request
import uuid
import zlib

BASE = os.environ.get("PRACTICAL_AI_BASE_URL", "http://127.0.0.1:3847").rstrip("/")
TOKEN = os.environ.get("PUBLISH_API_TOKEN", "")


def fail(message):
    print(message, file=sys.stderr)
    sys.exit(1)


def request(method, path, body=None, content_type="application/json"):
    if not TOKEN:
        fail("Set PUBLISH_API_TOKEN.")
    data = body if isinstance(body, bytes) or body is None else json.dumps(body).encode()
    headers = {"Authorization": f"Bearer {TOKEN}"}
    if data is not None and content_type:
        headers["Content-Type"] = content_type
    req = urllib.request.Request(BASE + path, data=data, method=method, headers=headers)
    try:
        with urllib.request.urlopen(req) as response:
            raw = response.read().decode()
            return json.loads(raw) if raw else None
    except urllib.error.HTTPError as error:
        detail = error.read().decode()
        fail(f"{method} {path} returned {error.code}\n{detail}")


def png(width, height, rgb=(228, 238, 232)):
    """A flat PNG, so the example does not need an image library."""

    def chunk(tag, data):
        return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)

    raw = b"".join(b"\x00" + bytes(rgb) * width for _ in range(height))
    return b"".join(
        [
            b"\x89PNG\r\n\x1a\n",
            chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)),
            chunk(b"IDAT", zlib.compress(raw, 9)),
            chunk(b"IEND", b""),
        ]
    )


def upload_image(alt):
    boundary = "----PracticalAI" + uuid.uuid4().hex
    image = png(640, 400)
    parts = [
        f"--{boundary}\r\nContent-Disposition: form-data; name=\"alt\"\r\n\r\n{alt}\r\n".encode(),
        (
            f"--{boundary}\r\n"
            f"Content-Disposition: form-data; name=\"file\"; filename=\"notes.png\"\r\n"
            f"Content-Type: image/png\r\n\r\n"
        ).encode()
        + image
        + b"\r\n",
        f"--{boundary}--\r\n".encode(),
    ]
    return request("POST", "/api/media", b"".join(parts), f"multipart/form-data; boundary={boundary}")


def main():
    slug = "notes-sorted-by-hand"
    topic = "ai-at-work"
    request(
        "PUT",
        f"/api/topics/en/{topic}",
        {
            "lang": "en",
            "slug": topic,
            "title": "AI at work",
            "description": "Methods for real work tasks.",
            "illustration": "work",
            "sortOrder": 2,
        },
    )
    image = upload_image("Notes sorted into three short lists")
    created = request(
        "PUT",
        f"/api/articles/en/{slug}",
        {
            "lang": "en",
            "slug": slug,
            "title": "Sort notes before you answer them",
            "description": "Ask for decisions, tasks and questions, and check that each one came from the notes.",
            "topic": topic,
            "status": "draft",
            "tags": ["notes"],
            "coverImage": {"url": image["url"], "alt": image["alt"]},
            "videoUrl": None,
            "sources": [],
            "bodyMarkdown": "\n".join(
                [
                    "## What you want",
                    "",
                    "A short list you can act on.",
                    "",
                    f"![{image['alt']}]({image['url']} \"Three lists, each traced to the notes\")",
                    "",
                    "## An example you can copy",
                    "",
                    "```prompt",
                    "Split the notes into decisions, tasks and open questions.",
                    "Quote the phrase each item came from.",
                    "If the notes do not name an owner, write \"not stated\".",
                    "```",
                ]
            ),
        },
    )
    print("created", created["status"], created["href"])
    preview = request("POST", "/api/preview", {"lang": "en", "slug": slug})
    print("preview", preview.get("previewUrl"))
    updated = request(
        "PUT",
        f"/api/articles/en/{slug}",
        {"title": "Sort notes before you answer them", "status": "published"},
    )
    print("updated", updated["status"], updated["publishedAt"])


if __name__ == "__main__":
    main()
