import asyncio
import ctypes
import os
import time
from playwright.async_api import async_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 hàm ẩn cửa sổ ngay lập tức khi khởi chạy
hide_console()
# ===================================================
# CẤU HÌNH
# -------------------------------------------------------------
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ACCOUNTS_FILE = os.path.join(BASE_DIR, "accounts.txt")
INTERVAL_SECONDS = 12 * 60 * 60 # 12 giờ (an toàn cho điểm danh 1 lần/ngày)
HEADLESS = True
# -------------------------------------------------------------

def load_accounts(file_path):
accounts = []
if not os.path.exists(file_path):
print(f"[-] File {file_path} không tồn tại!")
return accounts
with open(file_path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
if "|" in line:
user, pwd = line.split("|", 1)
elif ":" in line:
user, pwd = line.split(":", 1)
else:
continue
accounts.append((user.strip(), pwd.strip()))
return accounts


async def safe_goto(page, url, retries=3):
for attempt in range(1, retries + 1):
try:
await page.goto(url, wait_until="domcontentloaded", timeout=60000)
return True
except Exception as e:
print(f" [!] Lỗi tải trang ({attempt}/{retries}): {e}")
if attempt < retries:
await asyncio.sleep(2)
else:
raise e


async def process_account(browser, username, password):
print("\n==========================================")
print(f"[*] Đang xử lý tài khoản: {username}")

context = await browser.new_context()
page = await context.new_page()
page.on("dialog", lambda dialog: dialog.accept())
page.set_default_timeout(60000)
page.set_default_navigation_timeout(60000)

try:
# 1. Đăng nhập
print("[1] Đăng nhập...")
await safe_goto(page, "https://1900.fun/login.php")
await page.fill("input[name='username']", username)
await page.fill("input[name='password']", password)

async with page.expect_navigation(wait_until="domcontentloaded"):
await page.click("button[type='submit']")
await page.wait_for_timeout(1500)

# 2. Điểm danh
print("[2] Kiểm tra điểm danh hàng ngày...")
await safe_goto(page, "https://1900.fun/profile.php")
await page.wait_for_timeout(1200)

checkin_button = page.locator("button[name='checkin']")

if await checkin_button.count() > 0:
is_disabled = await checkin_button.is_disabled()
if not is_disabled:
print(" → Chưa điểm danh → Đang điểm danh...")
await checkin_button.click()
await page.wait_for_timeout(1800)
print(" → Điểm danh thành công!")
else:
print(" → Đã điểm danh rồi → Bỏ qua")
else:
# Thử tìm nút theo cách khác nếu selector cũ không còn
alt_button = page.locator("button:has-text('Điểm danh'), button:has-text('Check-in'), .checkin-btn")
if await alt_button.count() > 0:
print(" → Tìm thấy nút điểm danh (selector phụ) → Click...")
await alt_button.first.click()
await page.wait_for_timeout(1800)
print(" → Điểm danh thành công!")
else:
print(" → Không tìm thấy nút điểm danh")

# 3. Đăng xuất
print("[3] Đăng xuất...")
await safe_goto(page, "https://1900.fun/logout.php")
await page.wait_for_timeout(1000)
print(f"[+] Hoàn tất: {username}")

except Exception as e:
print(f"[-] Lỗi với {username}: {e}")
finally:
await context.close()
await asyncio.sleep(1.5)


async def run_automation():
accounts = load_accounts(ACCOUNTS_FILE)
if not accounts:
print("[-] Danh sách tài khoản trống!")
return

async with async_playwright() as p:
browser = await p.chromium.launch(headless=HEADLESS)
for username, password in accounts:
await process_account(browser, username, password)
await browser.close()


if __name__ == "__main__":
while True:
try:
print(f"\n==================== [ BẮT ĐẦU ĐIỂM DANH HÀNG NGÀY ] ====================")
asyncio.run(run_automation())
except Exception as err:
print(f"[!] Lỗi ngoài: {err}")

hours = INTERVAL_SECONDS // 3600
print(f"\n[⏳] Hoàn thành. Chờ {hours} giờ để chạy tiếp...")
time.sleep(INTERVAL_SECONDS)