#!/usr/bin/env python3
"""PrintOnline MCP server (stdio proxy) — ให้ Claude Desktop / Claude Code เรียก
SmartQuote/SmartLayout ของ printonline.co เป็น tool

ตัวนี้เป็น proxy บาง ๆ: ส่งทุกข้อความ MCP ต่อไปยัง Remote MCP ที่ https://printonline.co/mcp
(สมอง/รายการ tools อยู่ฝั่งเซิร์ฟเวอร์ — อัปเดต tool ใหม่โดยไม่ต้องโหลดไฟล์นี้ซ้ำ)

ทางเลือก 1 — ต่อ Remote MCP ตรง (ไม่ต้องใช้ไฟล์นี้เลย ถ้า client รองรับ HTTP):
  claude mcp add --transport http printonline https://printonline.co/mcp \\
    --header "X-Api-Key: pol_XXXX"

ทางเลือก 2 — ใช้ไฟล์นี้ (client ที่รับแต่ stdio เช่น Claude Desktop):
  1) ดาวน์โหลด: https://printonline.co/mcp-server.py
  2) API Key (pol_...) จากหน้า /account ของร้าน
  3) Claude Code:  claude mcp add printonline -e PRINTONLINE_API_KEY=pol_XXXX -- python printonline_mcp.py
     Claude Desktop (claude_desktop_config.json):
       "printonline": {"command": "python", "args": ["C:/path/printonline_mcp.py"],
                       "env": {"PRINTONLINE_API_KEY": "pol_XXXX"}}
  * ไม่ใส่คีย์ = ใช้ได้เฉพาะ quote_free_text (สูตรมาตรฐาน + โควตา guest)

Tools: quote_free_text · quote_multi_qty · make_quotation · save_order · list_orders · get_rate_card
ความปลอดภัย: คีย์ทำได้แค่คิดราคา/ออกเอกสาร/ดูออเดอร์ของร้านตัวเอง — แก้ตั้งค่า/ร้านอื่นไม่ได้
"""
import json
import os
import sys
import urllib.request

BASE = os.environ.get("PRINTONLINE_BASE", "https://printonline.co").rstrip("/")
KEY = os.environ.get("PRINTONLINE_API_KEY", "").strip()


def _post(msg):
    headers = {"Content-Type": "application/json"}
    if KEY:
        headers["X-Api-Key"] = KEY
    req = urllib.request.Request(BASE + "/mcp", data=json.dumps(msg).encode("utf-8"),
                                 headers=headers, method="POST")
    with urllib.request.urlopen(req, timeout=180) as r:
        return r.read().decode("utf-8").strip()


def main():
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        try:
            msg = json.loads(line)
        except ValueError:
            continue
        rid = msg.get("id")
        try:
            body = _post(msg)
            if rid is None:                      # notification — เซิร์ฟเวอร์ตอบ 202 ว่าง ไม่ต้อง echo
                continue
            if body:
                sys.stdout.write(body + "\n")
                sys.stdout.flush()
        except Exception as e:
            if rid is not None:
                sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": rid,
                                             "error": {"code": -32000, "message": str(e)}},
                                            ensure_ascii=False) + "\n")
                sys.stdout.flush()


if __name__ == "__main__":
    main()
