"""Prepare a MyDTF guest basket and print its one-time checkout link (Python 3.10+).

Example: python3 mydtf-cart.py --item design.png 85 85 5
Repeat --item FILE WIDTH_MM HEIGHT_MM QUANTITY for separate positions.
Give only the printed checkout link to the buyer. Files are sent to MyDTF.
"""
import argparse
import hashlib
import json
import mimetypes
import secrets
import sys
import uuid
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener

ORIGIN = "https://mydtf.ru"
MAX_BYTES = 50 * 1024 * 1024


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def run(items):
    opener = build_opener(NoRedirect())
    sequence = 0
    version = "2025-03-26"

    def post(path, data, headers):
        request = Request(ORIGIN + path, data=data, headers=headers, method="POST")
        try:
            with opener.open(request, timeout=90) as response:
                raw = response.read()
        except HTTPError as error:
            raise ValueError(f"MyDTF returned HTTP {error.code} for {path}") from None
        return json.loads(raw) if raw else {}

    def rpc(method, params, notify=False):
        nonlocal sequence
        sequence += 1
        body = {"jsonrpc": "2.0", "method": method, "params": params}
        if not notify:
            body["id"] = sequence
        answer = post("/api/agent/mcp", json.dumps(body).encode(), {
            "Content-Type": "application/json", "Accept": "application/json, text/event-stream",
            "MCP-Protocol-Version": version})
        if not notify and "result" not in answer:
            raise ValueError(f"MyDTF could not complete {method}")
        return answer.get("result")

    def tool(tool_name, **arguments):
        result = rpc("tools/call", {"name": tool_name, "arguments": arguments})
        data = result["structuredContent"]
        if result.get("isError") or not data.get("ok"):
            raise ValueError(tool_name + ": " + data.get("error", {}).get("code", "failed"))
        return data

    prepared = []
    for filename, width, height, quantity in items:
        path = Path(filename)
        width, height, quantity = int(width), int(height), int(quantity)
        if not (10 <= width <= 600 and 10 <= height <= 600 and 1 <= quantity <= 1000):
            raise ValueError("Use 10–600 mm per side and 1–1000 copies.")
        if not path.is_file() or not 0 < path.stat().st_size <= MAX_BYTES:
            raise ValueError("Choose a readable original up to 50 MiB.")
        prepared.append((path,width,height,quantity))
    if not 1 <= len(prepared) <= 100:
        raise ValueError("Choose between 1 and 100 positions.")
    init = rpc("initialize", {"protocolVersion": version, "capabilities": {},
        "clientInfo": {"name": "mydtf-file-client", "version": "1.0"}})
    version = init["protocolVersion"]
    rpc("notifications/initialized", {}, notify=True)
    guest = tool("mydtf_guest_start", name="Помощник покупателя")["guestAccess"]
    uploaded = {}
    expected = {}
    for path, width, height, quantity in prepared:
        with path.open("rb") as original:
            data = original.read(MAX_BYTES + 1)
        if not 0 < len(data) <= MAX_BYTES:
            raise ValueError("The original file size changed. Choose the file again.")
        digest = hashlib.sha256(data).hexdigest()
        if digest not in uploaded:
            boundary = secrets.token_hex(24)
            mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
            prefix = (f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="artwork"\r\n'
                      f'Content-Type: {mime}\r\n\r\n').encode()
            body = prefix + data + f"\r\n--{boundary}--\r\n".encode()
            asset = post("/api/agent/assets", body, {"Authorization": "Bearer " + guest,
                         "Content-Type": "multipart/form-data; boundary=" + boundary})["asset"]
            if asset["sha256"] != digest:
                raise ValueError("MyDTF did not confirm the original file.")
            uploaded[digest] = asset["id"]
        item = str(uuid.uuid4())
        tool("mydtf_cart_add", guestAccess=guest, itemId=item, assetId=uploaded[digest],
             widthMm=width, heightMm=height, quantity=quantity)
        expected[item] = (uploaded[digest], width, height, quantity)
    cart = tool("mydtf_state", guestAccess=guest)["cart"]
    actual = {row["id"]: (row["assetId"],row["widthMm"],row["heightMm"],row["quantity"]) for row in cart}
    if actual != expected:
        raise ValueError("The prepared basket differs from the requested items.")
    link = tool("mydtf_begin_checkout", guestAccess=guest)["checkoutUrl"]
    target = urlsplit(link)
    if (target.scheme, target.netloc, target.path) != ("https", "mydtf.ru", "/studio/agent-checkout") or not target.fragment.startswith("handoff="):
        raise ValueError("Unexpected checkout link.")
    return link


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--item", nargs=4, action="append", required=True,
                        metavar=("FILE", "WIDTH_MM", "HEIGHT_MM", "QUANTITY"))
    try:
        print(run(parser.parse_args().item))
    except (OSError, ValueError, KeyError) as error:
        sys.exit(str(error))
