import ctypes
import json
import math
import secrets
import random
import threading
import time
import webbrowser
from pathlib import Path
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse


HOST = "127.0.0.1"
PORT = 8765
DEFAULT_INTERVAL_SECONDS = 5 * 60 + 15
DEFAULT_START_DELAY_SECONDS = 5

MOUSEEVENTF_LEFTDOWN = 0x0002
MOUSEEVENTF_LEFTUP = 0x0004
VK_F8 = 0x77
VK_F9 = 0x78
SM_CXSCREEN = 0
SM_CYSCREEN = 1

user32 = ctypes.windll.user32
TOKEN_FILE = Path(__file__).with_name('.local-token')


def connection_token():
    if not TOKEN_FILE.exists():
        TOKEN_FILE.write_text(secrets.token_urlsafe(32), encoding='utf-8')
    return TOKEN_FILE.read_text(encoding='utf-8').strip()


ACCESS_TOKEN = connection_token()


class POINT(ctypes.Structure):
    _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]


def get_cursor_position():
    point = POINT()
    user32.GetCursorPos(ctypes.byref(point))
    return point.x, point.y


def left_click(x=None, y=None):
    if x is not None and y is not None:
        user32.SetCursorPos(int(x), int(y))
    user32.mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    user32.mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)


def get_safe_random_position():
    width = user32.GetSystemMetrics(SM_CXSCREEN)
    height = user32.GetSystemMetrics(SM_CYSCREEN)

    left_margin = 80
    right_margin = 80
    top_margin = 160
    bottom_margin = 90

    min_x = min(left_margin, max(0, width - 1))
    max_x = max(min_x, width - right_margin)
    min_y = min(top_margin, max(0, height - 1))
    max_y = max(min_y, height - bottom_margin)

    return random.randint(min_x, max_x), random.randint(min_y, max_y)


class ClickerState:
    def __init__(self):
        self.lock = threading.Lock()
        self.running = False
        self.interval_seconds = DEFAULT_INTERVAL_SECONDS
        self.start_delay_seconds = DEFAULT_START_DELAY_SECONDS
        self.mode = "fixed"
        self.radius = 100
        self.cycle_seconds = 8
        self.motion_started_at = None
        self.fixed_position = None
        self.last_click_at = None
        self.next_click_at = None
        self.message = "Dang dung"

    def snapshot(self):
        with self.lock:
            now = time.time()
            remaining = None
            if self.running and self.next_click_at:
                remaining = max(0, self.next_click_at - now)
            return {
                "running": self.running,
                "intervalSeconds": self.interval_seconds,
                "startDelaySeconds": self.start_delay_seconds,
                "mode": self.mode,
                "radius": self.radius,
                "cycleSeconds": self.cycle_seconds,
                "fixedPosition": self.fixed_position,
                "lastClickAt": self.last_click_at,
                "nextClickAt": self.next_click_at,
                "remainingSeconds": remaining,
                "message": self.message,
            }


state = ClickerState()


def parse_interval(value):
    try:
        interval = float(str(value).strip().replace(",", "."))
    except ValueError:
        raise ValueError("Khoang thoi gian phai la so.")
    if not math.isfinite(interval) or interval <= 0:
        raise ValueError("Khoang thoi gian phai lon hon 0.")
    return interval


def start_clicking(interval_seconds=None, mode=None, start_delay_seconds=None,
                   radius=None, cycle_seconds=None):
    # Validate all settings before changing the active run.
    interval = parse_interval(interval_seconds) if interval_seconds is not None else None
    delay = parse_interval(start_delay_seconds) if start_delay_seconds is not None else None
    new_radius = parse_interval(radius) if radius is not None else None
    new_cycle = parse_interval(cycle_seconds) if cycle_seconds is not None else None
    if new_cycle is not None and new_cycle < 0.5:
        raise ValueError("Moi vong can it nhat 0.5 giay.")
    with state.lock:
        if interval is not None:
            state.interval_seconds = interval
        if delay is not None:
            state.start_delay_seconds = delay
        if new_radius is not None:
            state.radius = new_radius
        if new_cycle is not None:
            state.cycle_seconds = new_cycle
        if mode in ("current", "fixed", "random_safe", "circle", "random_5_6"):
            state.mode = mode
        state.fixed_position = None
        state.motion_started_at = None
        state.running = True
        state.last_click_at = None
        if state.mode == "random_5_6":
            state.interval_seconds = random.uniform(300, 360)
            state.next_click_at = time.time() + state.interval_seconds
        else:
            state.next_click_at = time.time() + state.start_delay_seconds
        state.message = "Dang dem nguoc"


def stop_clicking():
    with state.lock:
        state.running = False
        state.next_click_at = None
        state.message = "Dang dung"


def clicker_loop():
    while True:
        # Serialize movement with Start/Stop so no stale action follows Stop.
        with state.lock:
            now = time.time()
            ready = state.running and (state.next_click_at is None or now >= state.next_click_at)
            if ready and state.mode == "circle":
                if state.motion_started_at is None:
                    width = max(1, user32.GetSystemMetrics(SM_CXSCREEN))
                    height = max(1, user32.GetSystemMetrics(SM_CYSCREEN))
                    state.radius = min(state.radius, (width - 1) / 2, (height - 1) / 2)
                    x, y = get_cursor_position()
                    r = state.radius
                    # Current pointer is the circle's rightmost point.
                    state.fixed_position = (max(r, min(width - 1 - r, x - r)),
                                            max(r, min(height - 1 - r, y)))
                    state.motion_started_at = time.monotonic()
                    state.next_click_at = None
                x, y = circle_position(state.fixed_position, state.radius,
                                       time.monotonic() - state.motion_started_at,
                                       state.cycle_seconds)
                user32.SetCursorPos(x, y)
                state.message = "Dang di chuyen vong tron (khong click)"
            elif ready:
                if state.mode == "fixed":
                    if state.fixed_position is None:
                        state.fixed_position = get_cursor_position()
                    left_click(*state.fixed_position)
                elif state.mode in ("random_safe", "random_5_6"):
                    left_click(*get_safe_random_position())
                else:
                    left_click()
                state.last_click_at = time.time()
                if state.mode == "random_5_6":
                    state.interval_seconds = random.uniform(300, 360)
                state.next_click_at = state.last_click_at + state.interval_seconds
                state.message = "Dang chay"
        time.sleep(0.016)


def circle_position(center, radius, elapsed, cycle_seconds):
    angle = math.tau * ((elapsed % cycle_seconds) / cycle_seconds)
    return (round(center[0] + radius * math.cos(angle)),
            round(center[1] + radius * math.sin(angle)))


def hotkey_loop():
    last_f8 = False
    last_f9 = False
    while True:
        f8_pressed = bool(user32.GetAsyncKeyState(VK_F8) & 0x8000)
        f9_pressed = bool(user32.GetAsyncKeyState(VK_F9) & 0x8000)

        if f8_pressed and not last_f8:
            try:
                start_clicking()
            except ValueError:
                pass
        if f9_pressed and not last_f9:
            stop_clicking()

        last_f8 = f8_pressed
        last_f9 = f9_pressed
        time.sleep(0.08)


HTML = r"""<!doctype html>
<html lang="vi">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Auto Clicker Local</title>
  <style>
    :root {
      color-scheme: light;
      font-family: Arial, sans-serif;
      background: #f5f7fb;
      color: #172033;
    }
    body {
      margin: 0;
      min-height: 100vh;
      display: grid;
      place-items: center;
    }
    main {
      box-sizing: border-box;
      width: min(560px, calc(100vw - 32px));
      background: #ffffff;
      border: 1px solid #d9e0ea;
      border-radius: 8px;
      padding: 22px;
      box-shadow: 0 12px 40px rgba(19, 32, 53, 0.12);
    }
    h1 {
      margin: 0 0 18px;
      font-size: 24px;
    }
    label {
      display: block;
      font-weight: 700;
      margin: 14px 0 6px;
    }
    input, select {
      width: 100%;
      box-sizing: border-box;
      border: 1px solid #b9c4d3;
      border-radius: 6px;
      padding: 10px 12px;
      font-size: 16px;
    }
    .grid {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      gap: 10px;
    }
    .actions {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 12px;
      margin-top: 18px;
    }
    button {
      border: 0;
      border-radius: 6px;
      padding: 12px 14px;
      font-size: 16px;
      font-weight: 700;
      cursor: pointer;
    }
    .start {
      background: #147a46;
      color: white;
    }
    .stop {
      background: #bd2f2f;
      color: white;
    }
    .status {
      margin-top: 18px;
      padding: 12px;
      border-radius: 6px;
      background: #eef3f8;
      line-height: 1.6;
    }
    .hint {
      color: #5c697a;
      font-size: 14px;
      margin-top: 14px;
    }
  </style>
</head>
<body>
  <main>
    <h1>Auto Clicker Local</h1>
    <section id="connection">
      <label for="token">Ma ket noi tren may Windows</label>
      <input id="token" type="password" autocomplete="off" placeholder="Dan ma tu trang localhost">
      <button id="connect" type="button">Ket noi</button>
      <p class="hint">Chay tool Windows tren cung may, mo <a href="http://127.0.0.1:8765" target="_blank" rel="noopener">localhost:8765</a> de lay ma.
      Cho phep truy cap mang cuc bo neu trinh duyet hoi.
      <a href="/downloads/autoclicker.py" id="download">Tai tool Windows (can Python)</a></p>
    </section>
    <div id="localConnection" hidden>
      <label for="localToken">Ma ket noi (dan vao trang domain cua ban)</label>
      <input id="localToken" type="password" readonly>
      <button id="copyToken" type="button">Sao chep ma</button>
    </div>

    <label>Khoang thoi gian</label>
    <div class="grid">
      <input id="minutes" type="number" min="0" step="1" value="5" title="Phut">
      <input id="seconds" type="number" min="0" step="1" value="15" title="Giay">
      <input id="total" type="number" min="0.1" step="0.1" value="315" title="Tong giay">
    </div>

    <label for="delay">Bat dau sau bao nhieu giay</label>
    <input id="delay" type="number" min="0.1" step="0.1" value="5">

    <label for="mode">Che do hoat dong</label>
    <select id="mode">
      <option value="random_5_6" selected>Click ngau nhien moi 5-6 phut trong vung chua le</option>
      <option value="circle">Di chuyen vong tron lien tuc (khong click)</option>
      <option value="fixed">Co dinh vi tri chuot sau dem nguoc</option>
      <option value="current">Theo vi tri chuot hien tai moi lan click</option>
      <option value="random_safe">Ngau nhien trong vung an toan cua man hinh</option>
    </select>
    <div class="hint" id="randomHint" hidden>
      Lan dau va sau moi click deu cho ngau nhien 300-360 giay.
      Vi tri click nam tren man hinh chinh, chua le tren 160px, duoi 90px, hai ben 80px.
      Vung nay van co the chua nut hoac lien ket cua trang.
    </div>

    <div id="motionSettings">
      <label for="radius">Ban kinh vong tron (pixel)</label>
      <input id="radius" type="number" min="1" step="1" value="100">
      <label for="cycle">Thoi gian moi vong (giay)</label>
      <input id="cycle" type="number" min="0.5" step="0.5" value="8">
    </div>

    <div class="actions">
      <button class="start" id="start">Start (F8)</button>
      <button class="stop" id="stop">Stop (F9)</button>
    </div>

    <div class="status" id="status">Dang tai...</div>
    <div class="hint">
      Bam Start, sau do dua chuot toi vung muon chay trong thoi gian dem nguoc.
      Che do vong tron lap lien tuc, khong nghi giua cac vong. Bam F9 de dung nhanh.
    </div>
  </main>

  <script>
    const embeddedToken = "__LOCAL_CONNECTION_TOKEN__";
    const isLocal = location.hostname === "127.0.0.1" || location.hostname === "localhost";
    let accessToken = isLocal ? embeddedToken : (sessionStorage.getItem("clickerToken") || "");
    const apiBase = isLocal ? "" : "http://127.0.0.1:8765";
    document.querySelector("#connection").hidden = isLocal;
    document.querySelector("#localConnection").hidden = !isLocal;
    document.querySelector("#localToken").value = isLocal ? embeddedToken : "";
    document.querySelector("#token").value = isLocal ? "" : accessToken;
    document.querySelector("#copyToken").addEventListener("click", async () => {
      await navigator.clipboard.writeText(embeddedToken);
      document.querySelector("#copyToken").textContent = "Da sao chep";
    });
    document.querySelector("#connect").addEventListener("click", async () => {
      accessToken = document.querySelector("#token").value.trim();
      sessionStorage.setItem("clickerToken", accessToken);
      await refresh();
    });
    const minutes = document.querySelector("#minutes");
    const seconds = document.querySelector("#seconds");
    const total = document.querySelector("#total");
    const delay = document.querySelector("#delay");
    const mode = document.querySelector("#mode");
    const statusBox = document.querySelector("#status");
    function updateMode() {
      const motion = mode.value === "circle";
      const randomTimed = mode.value === "random_5_6";
      document.querySelector("#motionSettings").hidden = !motion;
      document.querySelector("#randomHint").hidden = !randomTimed;
      minutes.disabled = seconds.disabled = total.disabled = motion || randomTimed;
      delay.disabled = randomTimed;
    }
    mode.addEventListener("change", updateMode);
    updateMode();

    let syncing = false;

    function updateTotal() {
      if (syncing) return;
      syncing = true;
      total.value = ((Number(minutes.value) || 0) * 60 + (Number(seconds.value) || 0)).toString();
      syncing = false;
    }

    function updateParts() {
      if (syncing) return;
      syncing = true;
      const value = Number(total.value) || 0;
      minutes.value = Math.floor(value / 60).toString();
      seconds.value = Math.round(value % 60).toString();
      syncing = false;
    }

    minutes.addEventListener("input", updateTotal);
    seconds.addEventListener("input", updateTotal);
    total.addEventListener("input", updateParts);

    async function api(path, body) {
      if (!accessToken) throw new Error("Nhap ma ket noi tu trang localhost tren may Windows.");
      const response = await fetch(apiBase + path, {
        method: body ? "POST" : "GET",
        headers: {"X-Clicker-Token": accessToken, ...(body ? {"Content-Type": "application/json"} : {})},
        signal: AbortSignal.timeout(5000),
        body: body ? JSON.stringify(body) : undefined
      });
      const data = await response.json();
      if (!response.ok) throw new Error(data.error || "Co loi xay ra");
      return data;
    }

    function formatTime(secondsValue) {
      if (secondsValue === null || secondsValue === undefined) return "-";
      const rounded = Math.ceil(secondsValue);
      const m = Math.floor(rounded / 60);
      const s = rounded % 60;
      return `${m} phut ${s} giay`;
    }

    function render(data) {
      const position = data.fixedPosition ? `${data.fixedPosition[0]}, ${data.fixedPosition[1]}` : "-";
      const modeText = {
        fixed: "Co dinh vi tri",
        current: "Theo con tro chuot",
        random_safe: "Ngau nhien vung an toan",
        random_5_6: "Click ngau nhien moi 5-6 phut (vung chua le)",
        circle: "Vong tron lien tuc - khong click"
      }[data.mode] || data.mode;
      statusBox.innerHTML = `
        <strong>Trang thai:</strong> ${data.running ? "Dang chay" : "Dang dung"}<br>
        <strong>Che do:</strong> ${modeText}<br>
        <strong>Thiet lap:</strong> ${data.mode === "circle" ? `Ban kinh ${data.radius}px, ${data.cycleSeconds}s/vong` : data.mode === "random_5_6" ? "Ngau nhien 5-6 phut moi lan" : formatTime(data.intervalSeconds)}<br>
        <strong>Cho lan dau:</strong> ${data.mode === "random_5_6" ? "Ngau nhien 5-6 phut" : formatTime(data.startDelaySeconds)}<br>
        <strong>Dem nguoc:</strong> ${data.running ? (data.mode === "circle" && data.remainingSeconds === null ? "Di chuyen lien tuc" : formatTime(data.remainingSeconds)) : "-"}<br>
        <strong>${data.mode === "circle" ? "Tam vong tron" : "Vi tri co dinh"}:</strong> ${position}
      `;
    }

    document.querySelector("#start").addEventListener("click", async () => {
      try {
        render(await api("/api/start", {
          intervalSeconds: Number(total.value),
          startDelaySeconds: Number(delay.value),
          mode: mode.value,
          radius: Number(document.querySelector("#radius").value),
          cycleSeconds: Number(document.querySelector("#cycle").value)
        }));
      } catch (error) {
        alert(error.message);
      }
    });

    document.querySelector("#stop").addEventListener("click", async () => {
      try { render(await api("/api/stop", {})); }
      catch (error) { statusBox.textContent = error.message; }
    });

    async function refresh() {
      try {
        const data = await api("/api/status");
        render(data);
      } catch (error) {
        statusBox.textContent = "Chua ket noi: " + error.message + " Kiem tra tool Windows va quyen truy cap mang cuc bo.";
      }
    }

    refresh();
    setInterval(refresh, 1000);
  </script>
</body>
</html>
"""


class RequestHandler(BaseHTTPRequestHandler):
    def end_headers(self):
        origin = self.headers.get("Origin", "")
        if self.path.startswith("/api/") and (origin.startswith("https://") or origin in (f"http://127.0.0.1:{PORT}", f"http://localhost:{PORT}")):
            self.send_header("Access-Control-Allow-Origin", origin)
            self.send_header("Vary", "Origin")
        self.send_header("Cache-Control", "no-store")
        super().end_headers()

    def authorized(self):
        host = self.headers.get("Host", "")
        if host not in (f"127.0.0.1:{PORT}", f"localhost:{PORT}"):
            self.send_json({"error": "Host khong hop le"}, 403)
            return False
        if not secrets.compare_digest(self.headers.get("X-Clicker-Token", ""), ACCESS_TOKEN):
            self.send_json({"error": "Ma ket noi khong dung"}, 401)
            return False
        return True

    def do_OPTIONS(self):
        self.send_response(204)
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type, X-Clicker-Token")
        self.send_header("Access-Control-Allow-Private-Network", "true")
        self.end_headers()

    def log_message(self, format, *args):
        return

    def send_json(self, data, status=200):
        body = json.dumps(data).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        path = urlparse(self.path).path
        if path == "/":
            if self.headers.get("Host") not in (f"127.0.0.1:{PORT}", f"localhost:{PORT}"):
                self.send_json({"error": "Host khong hop le"}, 403)
                return
            body = HTML.replace("__LOCAL_CONNECTION_TOKEN__", ACCESS_TOKEN).encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        if path == "/api/status":
            if not self.authorized():
                return
            self.send_json(state.snapshot())
            return
        self.send_json({"error": "Khong tim thay"}, 404)

    def do_POST(self):
        if not self.authorized():
            return
        path = urlparse(self.path).path
        content_length = int(self.headers.get("Content-Length", "0"))
        if content_length < 0 or content_length > 4096:
            self.send_json({"error": "Du lieu qua lon"}, 413)
            return
        raw_body = self.rfile.read(content_length) if content_length else b"{}"

        try:
            data = json.loads(raw_body.decode("utf-8"))
            if not isinstance(data, dict):
                raise ValueError()
        except (ValueError, UnicodeDecodeError):
            self.send_json({"error": "Du lieu gui len khong hop le"}, 400)
            return

        try:
            if path == "/api/start":
                start_clicking(
                    data.get("intervalSeconds"),
                    data.get("mode"),
                    data.get("startDelaySeconds"),
                    data.get("radius"),
                    data.get("cycleSeconds"),
                )
                self.send_json(state.snapshot())
                return
            if path == "/api/stop":
                stop_clicking()
                self.send_json(state.snapshot())
                return
        except ValueError as error:
            self.send_json({"error": str(error)}, 400)
            return

        self.send_json({"error": "Khong tim thay"}, 404)


def main():
    threading.Thread(target=clicker_loop, daemon=True).start()
    threading.Thread(target=hotkey_loop, daemon=True).start()

    server = ThreadingHTTPServer((HOST, PORT), RequestHandler)
    url = f"http://{HOST}:{PORT}"
    print(f"Auto Clicker dang chay tai {url}")
    print("Bam Ctrl+C trong cua so nay de tat server.")
    webbrowser.open(url)
    server.serve_forever()


if __name__ == "__main__":
    main()
