import http.server
import socketserver
import json
import os
import datetime
from urllib.request import Request, urlopen

PORT = 8080
DIRECTORY = os.path.dirname(os.path.abspath(__file__))
ORDERS_FILE = os.path.join(DIRECTORY, 'data', 'orders.json')
CONFIG_FILE = os.path.join(DIRECTORY, 'data', 'config.json')

def load_orders():
    if os.path.exists(ORDERS_FILE):
        with open(ORDERS_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    return []

def save_orders(orders):
    with open(ORDERS_FILE, 'w', encoding='utf-8') as f:
        json.dump(orders, f, ensure_ascii=False, indent=2)

def load_config():
    if os.path.exists(CONFIG_FILE):
        with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    return {}

def save_config(config):
    with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
        json.dump(config, f, ensure_ascii=False, indent=2)

def push_to_wechat(token, title, content):
    try:
        data = json.dumps({
            "token": token,
            "title": title,
            "content": content,
            "template": "txt"
        }).encode('utf-8')
        req = Request(
            'https://www.pushplus.plus/send',
            data=data,
            headers={'Content-Type': 'application/json'}
        )
        resp = urlopen(req, timeout=10)
        result = json.loads(resp.read().decode('utf-8'))
        print(f"PushPlus result: {result}")
        return result
    except Exception as e:
        print(f"PushPlus error: {e}")
        return None

class CustomHandler(http.server.SimpleHTTPRequestHandler):
    protocol_version = "HTTP/1.1"
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

    def _set_headers(self, content_type='application/json'):
        self.send_response(200)
        self.send_header('Content-Type', f'{content_type}; charset=utf-8')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.send_header('Content-Length', '0')
        self.send_header('Connection', 'close')
        self.end_headers()

    def _send_json(self, data):
        body = json.dumps(data, ensure_ascii=False).encode('utf-8')
        self.send_response(200)
        self.send_header('Content-Type', 'application/json; charset=utf-8')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.send_header('Content-Length', str(len(body)))
        self.send_header('Connection', 'close')
        self.end_headers()
        self.wfile.write(body)

    def do_OPTIONS(self):
        self._set_headers()

    def do_GET(self):
        if self.path == '/api/orders':
            self._send_json(load_orders())
        elif self.path == '/api/config':
            config = load_config()
            self._send_json({"has_token": bool(config.get('pushplus_token', ''))})
        else:
            super().do_GET()

    def do_POST(self):
        content_length = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(content_length)

        if self.path == '/api/order':
            self._handle_order(body)
        elif self.path == '/api/order/done':
            self._handle_done(body)
        elif self.path == '/api/orders/clear':
            save_orders([])
            self._send_json({"success": True})
        elif self.path == '/api/config':
            data = json.loads(body.decode('utf-8'))
            config = load_config()
            config['pushplus_token'] = data.get('token', '')
            save_config(config)
            self._send_json({"success": True})
        else:
            self.send_error(404)

    def _handle_order(self, body):
        order = json.loads(body.decode('utf-8'))
        order['timestamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        order['status'] = 'pending'

        orders = load_orders()
        orders.append(order)
        save_orders(orders)

        config = load_config()
        token = config.get('pushplus_token', '')
        wechat_result = None
        if token:
            dishes = order.get('dishes', [])
            dish_list = '\n'.join([f"  {d['name']} x{d['qty']}" for d in dishes])
            content = (
                f"下单人：{order.get('name', '匿名')}\n"
                f"时间：{order['timestamp']}\n"
                f"共 {len(dishes)} 道菜\n\n"
                f"{dish_list}"
            )
            wechat_result = push_to_wechat(token, '腾大厨收到新订单', content)

        self._send_json({
            "success": True,
            "message": "订单已提交",
            "wechat_pushed": wechat_result is not None
        })

    def _handle_done(self, body):
        data = json.loads(body.decode('utf-8'))
        idx = data.get('index', -1)
        orders = load_orders()
        if 0 <= idx < len(orders):
            orders[idx]['status'] = 'done'
            save_orders(orders)
        self._send_json({"success": True})

if __name__ == '__main__':
    with socketserver.ThreadingTCPServer(("", PORT), CustomHandler) as httpd:
        print(f"腾大厨味道 服务器启动 - 端口 {PORT}")
        print(f"菜单地址: http://localhost:{PORT}/family-menu-app.html")
        print(f"厨房看板: http://localhost:{PORT}/kitchen.html")
        httpd.serve_forever()
