#!/usr/bin/env python3
"""外贸邮件营销系统 — 本地服务器（静态文件 + 公司资产 REST API）

Usage: python server.py [port]
Default port: 8099
"""

import http.server
import json
import os
import socketserver
import sys
import time
import urllib.parse
from pathlib import Path

PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8099
ROOT = Path(__file__).parent
DB_FILE = ROOT / "assets_db.json"

# ---------- JSON Database ----------
def load_db():
    if not DB_FILE.exists():
        return {"contacts": [], "meta": {"created": time.strftime("%Y-%m-%d %H:%M:%S"), "total_saved": 0}}
    with open(DB_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def save_db(db):
    db["meta"]["updated"] = time.strftime("%Y-%m-%d %H:%M:%S")
    db["meta"]["total_saved"] = len(db["contacts"])
    with open(DB_FILE, "w", encoding="utf-8") as f:
        json.dump(db, f, ensure_ascii=False, indent=2)


class APIHandler(http.server.SimpleHTTPRequestHandler):
    """Serves static files + REST API for contact assets."""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=str(ROOT), **kwargs)

    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)

        if parsed.path == "/api/assets":
            db = load_db()
            self._send_json(db["contacts"])
            return
        elif parsed.path == "/api/assets/count":
            db = load_db()
            self._send_json({"count": len(db["contacts"])})
            return

        # Static file serving
        super().do_GET()

    def do_POST(self):
        parsed = urllib.parse.urlparse(self.path)

        if parsed.path == "/api/assets":
            length = int(self.headers.get("Content-Length", 0))
            body = self.rfile.read(length)
            try:
                new_contacts = json.loads(body)
            except json.JSONDecodeError:
                self._send_error(400, "Invalid JSON")
                return

            if not isinstance(new_contacts, list):
                self._send_error(400, "Expected a JSON array of contacts")
                return

            db = load_db()
            existing_emails = {c["email"] for c in db["contacts"]}
            added = 0
            skipped = 0

            for c in new_contacts:
                email = (c.get("email") or "").strip()
                if not email:
                    continue
                if email in existing_emails:
                    skipped += 1
                    continue
                db["contacts"].append({
                    "id": f"ast_{int(time.time() * 1000)}_{added}",
                    "name": c.get("name", "").strip(),
                    "email": email,
                    "company": c.get("company", "").strip(),
                    "industry": c.get("industry", "").strip(),
                    "country": c.get("country", "").strip(),
                    "position": c.get("position", "").strip(),
                    "source": c.get("source", "").strip(),
                    "mx_verified": c.get("mx_verified", False),
                    "saved_at": time.strftime("%Y-%m-%d %H:%M:%S"),
                    "tags": c.get("tags", []),
                })
                existing_emails.add(email)
                added += 1

            if added > 0:
                save_db(db)

            self._send_json({"ok": True, "added": added, "skipped": skipped, "total": len(db["contacts"])})
            return

        self._send_error(404, "Not found")

    def do_DELETE(self):
        parsed = urllib.parse.urlparse(self.path)

        if parsed.path == "/api/assets":
            qs = urllib.parse.parse_qs(parsed.query)
            ids = qs.get("id", [])
            if not ids:
                self._send_error(400, "Missing ?id=xxx parameter")
                return

            db = load_db()
            before = len(db["contacts"])
            db["contacts"] = [c for c in db["contacts"] if c["id"] not in ids]
            removed = before - len(db["contacts"])

            if removed > 0:
                save_db(db)

            self._send_json({"ok": True, "removed": removed, "total": len(db["contacts"])})
            return

        self._send_error(404, "Not found")

    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("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def _send_error(self, code, msg):
        body = json.dumps({"error": msg}).encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_OPTIONS(self):
        self.send_response(204)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.end_headers()

    def log_message(self, fmt, *args):
        # 安静模式 — 只记录 API 请求
        if "/api/" in str(args[0]):
            super().log_message(fmt, *args)


if __name__ == "__main__":
    # 初始化数据库文件
    if not DB_FILE.exists():
        db = {"contacts": [], "meta": {"created": time.strftime("%Y-%m-%d %H:%M:%S"), "total_saved": 0}}
        with open(DB_FILE, "w", encoding="utf-8") as f:
            json.dump(db, f, ensure_ascii=False, indent=2)
        print(f"[server] 已创建资产数据库: {DB_FILE}")

    server = socketserver.ThreadingTCPServer(("0.0.0.0", PORT), APIHandler)
    server.daemon_threads = True
    print(f"[server] 外贸邮件营销系统已启动: http://localhost:{PORT}/email-system.html")
    print(f"[server] 资产API: http://localhost:{PORT}/api/assets")
    print(f"[server] 按 Ctrl+C 停止服务器")

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\n[server] 服务器已停止")
        server.server_close()
