#!/usr/bin/env python3
"""
Pen Plotter bridge — https://zumisio.com/tools/pen-plotter/

Pen Plotter のページ（ブラウザ）と Bambu Lab A1 mini のあいだで命令を受け渡す小さなプログラム。
ブラウザはプリンターと直接話せないので、この Mac の上で中継する。

  使い方:  python3 bridge.py            （初回はプリンターの IP・シリアル番号・アクセスコードを聞く）
           python3 bridge.py --lan      （同じ Wi-Fi の iPhone などからも使う。初回はパスワードを決める）
           python3 bridge.py --setup    （設定をやり直す）
           python3 bridge.py --lan --password   （パスワードを決め直す）

必要なもの: Python 3.9 以上だけ（追加のインストールは不要）。
プリンター側: 設定 → ネットワーク で「LAN のみ」をオンにし、「開発者モード」をオンにする。

- ページとは http://127.0.0.1:48765 で話す。ふだんはこの Mac の外からはつながらない
- --lan のときだけ同じネットワークの端末からもつながる。この Mac 以外からはパスワードがないと動かせない
- zumisio.com とこの Mac 上のページ以外からの命令は受けない
- ベッドの外へ出る動きや、ノズルがベッドに近づきすぎる動きは、ページに関係なくここで止める

Pen Plotter と同じ GPL-3.0。プリンターとの通信の手順は BambuScribe（Animesh Varma）を参考にした。
"""

import argparse
import getpass
import hashlib
import hmac
import json
import os
import re
import socket
import ssl
import struct
import sys
import threading
import time
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

VERSION = 2
PORT = 48765
BED = 180.0
Z_MIN = 0.4          # ノズルがベッドに近づける下限（mm）。ペン先はこれより下に出ている前提
Z_MAX = 170.0
Z_SAFE = 30.0        # 原点合わせのあとに上げる高さ
XY_FEED_MAX = 12000
Z_FEED_MAX = 1200
CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.zumisio-pen-plotter.json')
SITE = 'https://zumisio.com'

ALLOWED_ORIGINS = re.compile(
    r'^(https://(www\.)?zumisio\.com'
    r'|https://([a-z0-9-]+\.)?home-page\.pages\.dev'
    r'|http://(localhost|127\.0\.0\.1)(:\d+)?)$'
)


def log(*a):
    print(time.strftime('%H:%M:%S'), *a, flush=True)


# ------------------------------------------------------------------ 設定
def load_config(path, force_setup=False):
    cfg = {}
    if os.path.exists(path) and not force_setup:
        try:
            with open(path) as f:
                cfg = json.load(f)
        except Exception:
            cfg = {}
    if all(cfg.get(k) for k in ('ip', 'serial', 'access_code')):
        return cfg
    print('\nプリンターの情報を入れてください（プリンターの画面の 設定 → ネットワーク / デバイス に出ています）')
    cfg['ip'] = input(f"  IP アドレス{' [' + cfg['ip'] + ']' if cfg.get('ip') else ''}: ").strip() or cfg.get('ip', '')
    cfg['serial'] = input(f"  シリアル番号{' [' + cfg['serial'] + ']' if cfg.get('serial') else ''}: ").strip().upper() or cfg.get('serial', '')
    code = getpass.getpass('  アクセスコード（8桁。入力しても表示されない）: ').strip()
    cfg['access_code'] = code or cfg.get('access_code', '')
    if not all(cfg.get(k) for k in ('ip', 'serial', 'access_code')):
        sys.exit('入力が足りないので終了します。')
    save_config(path, cfg)
    print(f'  {path} に保存しました（この Mac のあなただけが読める）\n')
    return cfg


def save_config(path, cfg):
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, 'w') as f:
        json.dump(cfg, f)


# ------------------------------------------------------------------ パスワード（--lan のとき）
PW_ITER = 200000


def _pw_hash(password, salt):
    return hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), bytes.fromhex(salt), PW_ITER).hex()


def ask_password(path, cfg):
    print('\niPhone などから使うときのパスワードを決めてください（この Mac 以外から動かすときに入れる）')
    while True:
        a = getpass.getpass('  パスワード（4文字以上。入力しても表示されない）: ')
        if len(a) < 4:
            print('  4文字以上にしてください')
            continue
        if getpass.getpass('  もう一度: ') != a:
            print('  2回の入力が違います。もう一度')
            continue
        break
    salt = os.urandom(16).hex()
    cfg['lan_password'] = {'salt': salt, 'hash': _pw_hash(a, salt)}
    save_config(path, cfg)
    print(f'  決めました（{path} には暗号のように変えた形で保存し、パスワードそのものは残さない）\n')


def lan_ip(printer_ip):
    """プリンターへ向かうときに使うこの Mac の IP（実際には何も送らない）"""
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.connect((printer_ip, 9))
            return s.getsockname()[0]
    except OSError:
        return None


# ------------------------------------------------------------------ MQTT（最小限の 3.1.1 クライアント）
def _enc_len(n):
    out = bytearray()
    while True:
        b = n % 128
        n //= 128
        out.append(b | 0x80 if n else b)
        if not n:
            return bytes(out)


def _str(s):
    b = s.encode('utf-8')
    return struct.pack('>H', len(b)) + b


class Printer:
    """A1 mini と MQTT over TLS（8883）で話す。切れたら自動でつなぎ直す。"""

    def __init__(self, cfg):
        self.ip = cfg['ip']
        self.serial = cfg['serial']
        self.code = cfg['access_code']
        self.port = int(cfg.get('port', 8883))
        self.sock = None
        self.wlock = threading.Lock()
        self.connected = False
        self.error = ''
        self.seq = int(time.time()) % 100000
        self.report = {}
        self.last_report = 0.0
        self.on_drop = None   # 接続が切れたときに呼ぶ
        threading.Thread(target=self._run, daemon=True).start()

    # 送る
    def _send(self, data):
        with self.wlock:
            if not self.sock:
                raise ConnectionError('プリンターにつながっていません')
            self.sock.sendall(data)

    def publish(self, payload):
        topic = f'device/{self.serial}/request'
        body = _str(topic) + json.dumps(payload, separators=(',', ':')).encode('utf-8')
        self._send(b'\x30' + _enc_len(len(body)) + body)

    def gcode(self, lines):
        self.seq += 1
        param = ''.join(f'{l.strip()} \n' for l in lines if l.strip())
        self.publish({'print': {'sequence_id': str(self.seq), 'command': 'gcode_line', 'param': param}})
        return self.seq

    def command(self, cmd):
        self.seq += 1
        self.publish({'print': {'sequence_id': str(self.seq), 'command': cmd}})

    # 受ける
    def _recv_exact(self, n):
        buf = b''
        while len(buf) < n:
            chunk = self.sock.recv(n - len(buf))
            if not chunk:
                raise ConnectionError('プリンターとの接続が切れました')
            buf += chunk
        return buf

    def _read_packet(self):
        h = self._recv_exact(1)[0]
        mult, length = 1, 0
        while True:
            b = self._recv_exact(1)[0]
            length += (b & 127) * mult
            mult *= 128
            if not b & 128:
                break
        return h, self._recv_exact(length) if length else b''

    def _connect(self):
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE   # プリンターの証明書は自己署名
        raw = socket.create_connection((self.ip, self.port), timeout=8)
        s = ctx.wrap_socket(raw, server_hostname=self.ip)
        cid = f'pen-plotter-{os.getpid()}'
        var = _str('MQTT') + bytes([4, 0xC2]) + struct.pack('>H', 30)
        payload = _str(cid) + _str('bblp') + _str(self.code)
        body = var + payload
        s.sendall(b'\x10' + _enc_len(len(body)) + body)
        self.sock = s
        h, data = self._read_packet()
        if h >> 4 != 2 or len(data) < 2:
            raise ConnectionError('プリンターから想定外の返事がありました')
        if data[1] != 0:
            raise PermissionError({4: 'アクセスコードが違います', 5: '接続を拒否されました（LAN のみモード・開発者モードを確かめてください）'}.get(data[1], f'接続を拒否されました（コード {data[1]}）'))
        sub = struct.pack('>H', 1) + _str(f'device/{self.serial}/report') + b'\x00'
        s.sendall(b'\x82' + _enc_len(len(sub)) + sub)
        s.settimeout(None)
        self.publish({'pushing': {'sequence_id': '0', 'command': 'pushall'}})

    def _pinger(self, sock):
        while self.sock is sock:
            time.sleep(15)
            try:
                self._send(b'\xc0\x00')
            except Exception:
                return

    def _run(self):
        delay = 2
        while True:
            try:
                log(f'プリンター {self.ip} につないでいます…')
                self._connect()
                self.connected, self.error, delay = True, '', 2
                log('プリンターにつながりました')
                threading.Thread(target=self._pinger, args=(self.sock,), daemon=True).start()
                while True:
                    h, data = self._read_packet()
                    if h >> 4 == 3:
                        qos = (h >> 1) & 3
                        tl = struct.unpack('>H', data[:2])[0]
                        off = 2 + tl
                        if qos:
                            pid = data[off:off + 2]
                            off += 2
                            if qos == 1:
                                self._send(b'\x40\x02' + pid)
                        self._on_message(data[off:])
            except Exception as e:
                msg = str(e) or e.__class__.__name__
                if isinstance(e, (socket.timeout, TimeoutError)):
                    msg = 'プリンターが応答しません（IP アドレス・同じ Wi-Fi か・LAN のみモードを確かめてください）'
                elif isinstance(e, ConnectionRefusedError):
                    msg = '接続を断られました（LAN のみモード・開発者モードを確かめてください）'
                if msg != self.error:
                    log('つながりません:', msg)
                was = self.connected
                self.connected, self.error = False, msg
                if was and self.on_drop:
                    self.on_drop()
                try:
                    if self.sock:
                        self.sock.close()
                except Exception:
                    pass
                self.sock = None
                time.sleep(delay)
                delay = min(delay * 2, 20)

    def _on_message(self, raw):
        try:
            msg = json.loads(raw.decode('utf-8', 'replace'))
        except Exception:
            return
        p = msg.get('print')
        if isinstance(p, dict):
            for k in ('gcode_state', 'mc_print_stage', 'print_error', 'nozzle_temper', 'bed_temper', 'home_flag', 'sdcard'):
                if k in p:
                    self.report[k] = p[k]
            if p.get('command') == 'gcode_line' and p.get('result') and p.get('result') != 'success':
                log('プリンターが G-code を受け付けませんでした:', p.get('reason') or p.get('result'))
            self.last_report = time.time()


# ------------------------------------------------------------------ 位置の管理と安全の確かめ
class Machine:
    def __init__(self, printer):
        self.p = printer
        self.lock = threading.Lock()
        self.homed = False
        self.pos = {'x': None, 'y': None, 'z': None}
        self.busy_until = 0.0
        printer.on_drop = self._dropped

    def _dropped(self):
        # 切れている間にプリンターの電源が入れ直されると位置が分からなくなるので、原点合わせからやり直してもらう
        if self.homed:
            self.homed = False
            self.busy_until = 0
            log('プリンターとの接続が切れたので、原点合わせからやり直してください')

    def _wait_estimate(self, sec):
        now = time.time()
        self.busy_until = max(self.busy_until, now) + sec

    def home(self):
        with self.lock:
            mid = BED / 2
            self.p.gcode(['M104 S0', 'M140 S0', 'M106 S0', 'G28', 'G90', f'G1 Z{Z_SAFE:.1f} F{Z_FEED_MAX}',
                          f'G0 X{mid:.1f} Y{mid:.1f} F6000', 'M400'])
            self.homed = True
            self.pos = {'x': mid, 'y': mid, 'z': Z_SAFE}
            self.busy_until = time.time() + 45
            log('原点合わせを始めました')

    def run(self, lines):
        """許した命令だけを、位置を追いながら送る。1つでも範囲外なら何も送らない。"""
        with self.lock:
            if not self.homed:
                raise ValueError('先に原点合わせをしてください')
            pos = dict(self.pos)
            out, sec = ['G90'], 0.0
            for raw in lines:
                line = str(raw).split(';')[0].strip().upper()
                if not line:
                    continue
                m = re.match(r'^(G0|G1|G4|M400)\b(.*)$', line)
                if not m:
                    raise ValueError(f'使えない命令です: {line}')
                cmd, rest = m.group(1), m.group(2)
                words = dict((w[0], float(w[1:])) for w in rest.split() if re.match(r'^[XYZFPS]-?\d+(\.\d+)?$', w))
                if len(words) != len(rest.split()):
                    raise ValueError(f'読めない値があります: {line}')
                if cmd == 'G4':
                    ms = words.get('P', 0) + words.get('S', 0) * 1000
                    if not 0 <= ms <= 5000:
                        raise ValueError('待ち時間は 5 秒までです')
                    out.append(f'G4 P{int(ms)}')
                    sec += ms / 1000
                    continue
                if cmd == 'M400':
                    out.append('M400')
                    continue
                new = dict(pos)
                for a in 'XYZ':
                    if a in words:
                        new[a.lower()] = words[a]
                if not (0 <= new['x'] <= BED and 0 <= new['y'] <= BED):
                    raise ValueError(f'ベッドの外へは動かせません（X{new["x"]:.1f} Y{new["y"]:.1f}）')
                if not (Z_MIN <= new['z'] <= Z_MAX):
                    raise ValueError(f'Z は {Z_MIN}〜{Z_MAX:.0f} mm の間だけです（Z{new["z"]:.2f}）')
                moves_xy = new['x'] != pos['x'] or new['y'] != pos['y']
                moves_z = new['z'] != pos['z']
                if moves_xy and moves_z:
                    raise ValueError('XY と Z は別々の行で動かしてください')
                f = words.get('F', 3000)
                f = max(60.0, min(f, Z_FEED_MAX if moves_z else XY_FEED_MAX))
                parts = [cmd] + [f'{a}{new[a.lower()]:.3f}' for a in 'XYZ' if a in words] + [f'F{int(f)}']
                out.append(' '.join(parts))
                dist = abs(new['z'] - pos['z']) if moves_z else ((new['x'] - pos['x']) ** 2 + (new['y'] - pos['y']) ** 2) ** 0.5
                sec += dist / (f / 60) + 0.05
                pos = new
            self.p.gcode(out)
            self.pos = pos
            self._wait_estimate(sec * 1.2 + 0.1)
            return sec

    def stop(self):
        with self.lock:
            try:
                self.p.gcode(['M410'])
                self.p.command('stop')
            finally:
                self.homed = False
                self.busy_until = 0
            log('止めました。もう一度使うときは原点合わせから')

    def release(self):
        with self.lock:
            self.p.gcode(['M18'])
            self.homed = False
            log('モーターを止めました（手で動かせます）')

    def status(self):
        return {
            'bridge': VERSION,
            'printer': {'connected': self.p.connected, 'error': self.p.error, 'ip': self.p.ip,
                        'state': self.p.report.get('gcode_state'), 'nozzle_temp': self.p.report.get('nozzle_temper')},
            'homed': self.homed,
            'pos': self.pos,
            'busy_ms': max(0, int((self.busy_until - time.time()) * 1000)),
            'limits': {'bed': BED, 'z_min': Z_MIN, 'z_max': Z_MAX},
        }


# ------------------------------------------------------------------ HTTP（ページとの窓口）
_page_cache = {}


class Handler(BaseHTTPRequestHandler):
    server_version = 'PenPlotterBridge/1'
    machine = None
    lan = False          # --lan のとき True
    password = None      # {'salt', 'hash'}
    _good_keys = set()   # 一度確かめたパスワード（毎回の計算を省く）
    _fail_lock = threading.Lock()

    def log_message(self, *a):
        pass

    def _from_this_mac(self):
        return self.client_address[0] in ('127.0.0.1', '::1', '::ffff:127.0.0.1')

    def _origin_ok(self):
        hostport = self.headers.get('Host') or ''
        host = hostport.rsplit(':', 1)[0] if not hostport.startswith('[') else hostport
        # DNS リバインディング対策：名前で来た依頼は受けない（--lan では IP と .local の名前だけ受ける）
        ok_host = host in ('127.0.0.1', 'localhost') or (
            self.lan and (re.fullmatch(r'\d{1,3}(\.\d{1,3}){3}', host) or host.endswith('.local')))
        if not ok_host:
            return False
        origin = self.headers.get('Origin')
        return origin is None or bool(ALLOWED_ORIGINS.match(origin)) or origin == f'http://{hostport}'

    def _auth_ok(self):
        """この Mac からの依頼はそのまま通す。ほかの端末からはパスワードが要る"""
        if self._from_this_mac():
            return True
        if not (self.lan and self.password):
            return False
        key = self.headers.get('X-Pen-Key') or ''
        if key in Handler._good_keys:
            return True
        if key and hmac.compare_digest(_pw_hash(key, self.password['salt']), self.password['hash']):
            Handler._good_keys.add(key)
            return True
        with Handler._fail_lock:
            time.sleep(1)   # 当てずっぽうで試されにくくする
        return False

    def _deny(self):
        key = self.headers.get('X-Pen-Key')
        return self._json(401, {'ok': False, 'auth': True,
                                'message': 'パスワードが違います。' if key else 'パスワードを入れてください。'})

    def _cors(self):
        origin = self.headers.get('Origin')
        if origin and ALLOWED_ORIGINS.match(origin):
            self.send_header('Access-Control-Allow-Origin', origin)
            self.send_header('Vary', 'Origin')

    def _json(self, code, obj):
        body = json.dumps(obj, ensure_ascii=False).encode('utf-8')
        self.send_response(code)
        self._cors()
        self.send_header('Content-Type', 'application/json; charset=utf-8')
        self.send_header('Cache-Control', 'no-store')
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_OPTIONS(self):
        if not self._origin_ok():
            self.send_response(403)
            self.end_headers()
            return
        self.send_response(204)
        self._cors()
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, X-Pen-Key')
        self.send_header('Access-Control-Allow-Private-Network', 'true')
        self.send_header('Access-Control-Max-Age', '600')
        self.end_headers()

    def do_GET(self):
        if not self._origin_ok():
            return self._json(403, {'ok': False, 'message': 'このページからは使えません'})
        if self.path == '/status':
            if not self._auth_ok():
                return self._deny()
            return self._json(200, {'ok': True, **self.machine.status()})
        # Safari など、https のページから 127.0.0.1 に話せないブラウザ向けに、ツールのページをここから配る
        if self.path in ('/', '/index.html'):
            self.send_response(302)
            self.send_header('Location', '/tools/pen-plotter/')
            self.end_headers()
            return
        if self.path.startswith('/tools/pen-plotter/') or self.path.startswith('/fonts/') or self.path == '/favicon.svg':
            return self._proxy()
        self._json(404, {'ok': False, 'message': 'not found'})

    def _proxy(self):
        path = self.path.split('?')[0]
        if path.endswith('/index.html'):
            path = path[:-len('index.html')]
        if '..' in path:
            return self._json(400, {'ok': False})
        try:
            # サイトが新しくなったら追いつけるよう、取ってきたページは 30 秒だけ使い回す
            hit = _page_cache.get(path)
            if not hit or time.time() - hit[0] > 30:
                req = urllib.request.Request(SITE + path, headers={'User-Agent': 'Mozilla/5.0 (Macintosh) PenPlotterBridge/1'})
                with urllib.request.urlopen(req, timeout=20) as r:
                    hit = _page_cache[path] = (time.time(), r.headers.get('Content-Type', 'application/octet-stream'), r.read())
            _, ctype, body = hit
        except Exception as e:
            return self._json(502, {'ok': False, 'message': f'{SITE} からページを取れませんでした: {e}'})
        self.send_response(200)
        self.send_header('Content-Type', ctype)
        self.send_header('Content-Length', str(len(body)))
        self.send_header('Cache-Control', 'no-cache')
        self.end_headers()
        self.wfile.write(body)

    def do_POST(self):
        if not self._origin_ok():
            return self._json(403, {'ok': False, 'message': 'このページからは使えません'})
        if not self._auth_ok():
            return self._deny()
        if (self.headers.get('Content-Type') or '').split(';')[0].strip() != 'application/json':
            return self._json(415, {'ok': False, 'message': 'JSON で送ってください'})
        try:
            n = int(self.headers.get('Content-Length') or 0)
            data = json.loads(self.rfile.read(min(n, 200000)) or b'{}')
        except Exception:
            return self._json(400, {'ok': False, 'message': '読めない依頼です'})
        m = self.machine
        try:
            if not m.p.connected and self.path != '/stop':
                return self._json(503, {'ok': False, 'message': 'プリンターにつながっていません。' + (m.p.error or '')})
            if self.path == '/home':
                m.home()
            elif self.path == '/run':
                lines = data.get('lines')
                if not isinstance(lines, list) or len(lines) > 400:
                    raise ValueError('命令の数が多すぎます')
                m.run(lines)
            elif self.path == '/stop':
                m.stop()
            elif self.path == '/release':
                m.release()
            else:
                return self._json(404, {'ok': False, 'message': 'not found'})
        except ValueError as e:
            return self._json(400, {'ok': False, 'message': str(e), **m.status()})
        except Exception as e:
            return self._json(500, {'ok': False, 'message': str(e), **m.status()})
        self._json(200, {'ok': True, **m.status()})


class Server(ThreadingHTTPServer):
    daemon_threads = True

    def handle_error(self, request, client_address):
        # 相手が途中で接続を切っただけのときは、長いエラーを出さずに1行で知らせる
        e = sys.exc_info()[1]
        if isinstance(e, OSError):
            log(f'{client_address[0]} との接続が途中で切れました（{e.strerror or e}）')
        else:
            super().handle_error(request, client_address)


def main():
    ap = argparse.ArgumentParser(description='Pen Plotter と A1 mini をつなぐ中継プログラム')
    ap.add_argument('--setup', action='store_true', help='プリンターの設定をやり直す')
    ap.add_argument('--lan', action='store_true', help='同じネットワークの iPhone などからも使えるようにする（パスワードが要る）')
    ap.add_argument('--password', action='store_true', help='--lan のパスワードを決め直す')
    ap.add_argument('--port', type=int, default=PORT)
    ap.add_argument('--config', default=CONFIG_PATH, help=argparse.SUPPRESS)
    args = ap.parse_args()
    cfg = load_config(args.config, args.setup)
    if args.lan and (args.password or not cfg.get('lan_password')):
        ask_password(args.config, cfg)
    Handler.machine = Machine(Printer(cfg))
    Handler.lan = args.lan
    Handler.password = cfg.get('lan_password') if args.lan else None
    try:
        srv = Server(('0.0.0.0' if args.lan else '127.0.0.1', args.port), Handler)
    except OSError:
        sys.exit(f'ポート {args.port} が使われています。中継プログラムがもう動いていないか確かめてください。')
    print(f'\n中継プログラムが動いています。Pen Plotter のページで「つなぐ」を押してください。')
    print(f'  https://zumisio.com/tools/pen-plotter/')
    print(f'  （Safari でつながらないときは http://127.0.0.1:{args.port}/ を開く）')
    if args.lan:
        ip = lan_ip(cfg['ip'])
        print(f'\n  iPhone など（同じ Wi-Fi）からは、Safari でこのアドレスを開き、決めたパスワードを入れる:')
        print(f'    http://{ip or "この Mac の IP アドレス"}:{args.port}/')
        print('  Mac に「受け入れますか」と出たら「許可」を押す')
    print('  終わるときは Control + C\n')
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        print('\n終了しました')


if __name__ == '__main__':
    main()
