import ctypes
import os
import subprocess
import sys
import time
from playwright.sync_api import sync_playwright

USERNAME = "hoangchan"
PASSWORD = "ab270894"
LOGIN_URL = "https://forum.vdevs.net/login/"
FARM_URL = "https://forum.vdevs.net/farm/star-fruit-tree"

# Vòng lặp 6 tiếng = 21600 giây (chia nhỏ để thoát gọn nếu cần)
SLEEP_SECONDS = 6 * 60 * 60


# --- 1. Ẩn cửa sổ CMD ngay khi khởi động ---
def hide_console():
try:
hwnd = ctypes.windll.kernel32.GetConsoleWindow()
if hwnd:
ctypes.windll.user32.ShowWindow(hwnd, 0)
except Exception:
pass


# --- 2. Tự động khởi động cùng Windows ---
def add_to_startup():
"""Tạo shortcut trong thư mục Startup của Windows bằng PowerShell."""
try:
startup_dir = os.path.join(
os.environ["APPDATA"],
r"Microsoft\Windows\Start Menu\Programs\Startup",
)
os.makedirs(startup_dir, exist_ok=True)
shortcut_path = os.path.join(startup_dir, "AutoHarvest.lnk")

if getattr(sys, "frozen", False):
# Nếu đã đóng gói thành file .exe
target_path = sys.executable
arguments = ""
working_dir = os.path.dirname(sys.executable)
else:
# Nếu chạy file .py: ưu tiên pythonw.exe để không bật cửa sổ CMD
script_path = os.path.abspath(__file__)
python_dir = os.path.dirname(sys.executable)
pythonw = os.path.join(python_dir, "pythonw.exe")
target_path = pythonw if os.path.exists(pythonw) else sys.executable
arguments = f'"{script_path}"'
working_dir = os.path.dirname(script_path)

ps_script = (
f'$WshShell = New-Object -ComObject WScript.Shell; '
f'$Shortcut = $WshShell.CreateShortcut("{shortcut_path}"); '
f'$Shortcut.TargetPath = "{target_path}"; '
f'$Shortcut.Arguments = \'{arguments}\'; '
f'$Shortcut.WorkingDirectory = "{working_dir}"; '
f'$Shortcut.Save()'
)

subprocess.run(
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps_script],
check=False,
creationflags=subprocess.CREATE_NO_WINDOW,
)
except Exception:
pass


# --- 3. Thao tác Thu Hoạch ---
def run_harvest_job():
"""Đăng nhập và thu hoạch cây khế."""
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context(
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
)
page = context.new_page()

try:
page.goto(LOGIN_URL, wait_until="domcontentloaded", timeout=60000)
page.fill("#account", USERNAME)
page.fill("#password", PASSWORD)
page.click("input[type='submit'][value='Đăng nhập']")
page.wait_for_load_state("domcontentloaded")

page.goto(FARM_URL, wait_until="domcontentloaded", timeout=60000)

harvest_button = page.locator("input[type='submit'][value='Thu hoạch']")
if harvest_button.count() > 0:
harvest_button.first.click()
page.wait_for_timeout(3000)
except Exception:
pass
finally:
browser.close()


# --- 4. Vòng lặp 6 giờ ---
def main():
hide_console()
add_to_startup()

while True:
run_harvest_job()
time.sleep(SLEEP_SECONDS)


if __name__ == "__main__":
main()