import time
import random
import ctypes
from playwright.sync_api import sync_playwright

# ================== ẨN CỬA SỔ CMD ==================
def hide_console():
try:
hwnd = ctypes.windll.kernel32.GetConsoleWindow()
if hwnd:
ctypes.windll.user32.ShowWindow(hwnd, 0) # 0 = SW_HIDE
except Exception:
pass

# Gọi ngay khi khởi chạy
hide_console()
# ===================================================

# ================== CẤU HÌNH ==================
USERNAME = "hoangchan" # <-- điền username
PASSWORD = "ab270894@" # <-- điền password
HOME_URL = "https://dorew.ovh/"
FARM_URL = "https://dorew.ovh/farm/star_fruit_tree"

# Thời gian chờ giữa các lần chạy (giây)
# Cấp 11 ~6.3 giờ → nên để 6.5 ~ 7 giờ
WAIT_SECONDS = 8 * 3600
HEADLESS = True # False nếu muốn xem trình duyệt
# ==============================================


def human_delay(min_s=1.5, max_s=3.2):
"""Delay ngẫu nhiên giống người thật"""
time.sleep(random.uniform(min_s, max_s))


def run_harvest_job():
print("Đang khởi động trình duyệt...")
with sync_playwright() as p:
browser = p.chromium.launch(headless=HEADLESS)
context = browser.new_context(
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
viewport={"width": 1366, "height": 768}
)
page = context.new_page()

try:
# ========== BƯỚC 1: Vào trang chủ ==========
print("[Dorew] Đang vào trang chủ...")
page.goto(HOME_URL, wait_until="domcontentloaded", timeout=60000)
human_delay(2.0, 3.5)

# ========== BƯỚC 2: Đăng nhập bằng form không captcha ==========
print("[Dorew] Đang đăng nhập...")
# Điền tài khoản
page.fill('input[name="account"]', USERNAME)
human_delay(0.8, 1.5)
# Điền mật khẩu
page.fill('input[name="password"]', PASSWORD)
human_delay(0.8, 1.5)

# Đảm bảo checkbox "Ghi nhớ" được tick (nếu có)
remember = page.locator('input[name="remember"]')
if remember.count() > 0 and not remember.is_checked():
remember.check()

# Click nút Đăng nhập
page.click('button[type="submit"]:has-text("Đăng nhập")')
page.wait_for_load_state("domcontentloaded")
human_delay(2.5, 4.0)

# Kiểm tra đăng nhập thành công
if page.locator("text=Đăng xuất").count() > 0 or page.locator("a[href*='/logout']").count() > 0:
print("[Dorew] Đăng nhập thành công!")
else:
print("[Dorew] Có thể đăng nhập thất bại. Kiểm tra lại username/password.")
# Vẫn tiếp tục thử vào trang farm

# ========== BƯỚC 3: Vào trang Cây Khế ==========
print("[Dorew] Đang chuyển tới trang Cây Khế...")
page.goto(FARM_URL, wait_until="domcontentloaded", timeout=60000)
human_delay(2.5, 4.0)

# ========== BƯỚC 4: Tìm và bấm nút Thu hoạch ==========
print("[Dorew] Đang kiểm tra nút Thu hoạch...")
harvest_selectors = [
"button:has-text('Thu hoạch')",
"button:has-text('Thu Hoạch')",
"input[type='submit'][value*='Thu hoạch']",
"input[type='submit'][value*='Thu Hoạch']",
"a:has-text('Thu hoạch')",
"form[action*='harvest'] button",
"form[action*='harvest'] input[type='submit']",
"button.btn:has-text('Thu')",
]

harvested = False
for sel in harvest_selectors:
btn = page.locator(sel)
if btn.count() > 0 and btn.first.is_visible():
print(f"[Dorew] Tìm thấy nút → {sel}")
human_delay(1.8, 3.0)
btn.first.click()
human_delay(3.5, 5.0)
print("✅ Thu hoạch Cây Khế thành công!")
harvested = True
break

if not harvested:
# Kiểm tra timer còn lại
timer = page.locator("#sft_timer")
if timer.count() > 0:
remaining = timer.inner_text().strip()
print(f"[Dorew] Cây chưa chín. Thời gian còn lại: {remaining}")
else:
print("[Dorew] Không tìm thấy nút Thu hoạch và cũng không thấy timer.")

except Exception as e:
print(f"❌ Lỗi trong quá trình thực thi: {e}")
finally:
browser.close()


def main():
while True:
run_harvest_job()
print(f"\n⏳ Đang chờ {WAIT_SECONDS / 3600:.1f} giờ cho lượt thu hoạch tiếp theo...\n")
time.sleep(WAIT_SECONDS)


if __name__ == "__main__":
main()