import asyncio
import os
import ctypes
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)
except Exception:
pass

hide_console()

# -------------------------------------------------------------
# CẤU HÌNH CÀI ĐẶT
# -------------------------------------------------------------
TOTAL_CAGES = 3
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ờ
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 "|" in line and not line.startswith("#"):
user, pwd = line.split("|", 1)
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 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:
print("\n==========================================")
print(f"[*] Đang xử lý tài khoản: {username}")
context = await browser.new_context()
page = await context.new_page()

# Tự động bấm "OK" cho các hộp thoại xác nhận
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] Mở trang đă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 (kiểm tra đã điểm danh chưa)
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(1000)

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 → Tiến hành điểm danh...")
await checkin_button.click()
await page.wait_for_timeout(1500)
print(" -> Điểm danh thành công!")
else:
print(" -> Đã điểm danh rồi → Bỏ qua")
else:
print(" -> Không tìm thấy nút điểm danh (có thể đã điểm danh hoặc trang thay đổi)")

# 3. BÁN TẤT CẢ CÁC CHUỒNG HIỆN CÓ
print("[3] BÁN VẬT NUÔI: Đang thực hiện bán cho từng chuồng...")
for cage_idx in range(TOTAL_CAGES): # 0, 1, 2
await safe_goto(page, "https://1900.fun/nongtrai/vatnuoi.php")
await page.wait_for_timeout(1000)

sell_btn = page.locator(f"a[href='?harvest={cage_idx}']")
if await sell_btn.count() > 0:
async with page.expect_navigation(wait_until="domcontentloaded"):
await sell_btn.click()
print(f" -> Đã bán thành công vật nuôi ở Chuồng {cage_idx + 1}")
await page.wait_for_timeout(1500)
else:
print(f" -> Chuồng {cage_idx + 1} không có vật nuôi để bán hoặc đã trống.")

# 4. PHÂN TÍCH DỮ LIỆU ĐỂ CHỌN VẬT NUÔI CẤP CAO NHẤT
print("[4] Đang tính toán chọn vật nuôi tối ưu theo Cấp độ & Số xu...")
await safe_goto(page, "https://1900.fun/nongtrai/vatnuoi.php")
await page.wait_for_timeout(1000)

animal_data = await page.evaluate("""() => {
return {
animals: typeof animals !== 'undefined' ? animals : [],
userLevel: typeof userLevel !== 'undefined' ? userLevel : 1,
userMoney: typeof userMoney !== 'undefined' ? userMoney : 0
};
}""")

animals = animal_data.get("animals", [])
user_level = animal_data.get("userLevel", 1)
user_money = animal_data.get("userMoney", 0)

print(f" -> Cấp trại: {user_level} | Số xu hiện có: {user_money:,} xu")

affordable_animals = [
a for a in animals
if user_level >= a.get("level_required", 1) and user_money >= a.get("price", 0)
]

if not affordable_animals:
print(" -> [!] Không đủ tiền hoặc cấp độ không đủ để mua bất kỳ vật nuôi nào!")
selected_animal_id = None
else:
best_animal = max(affordable_animals, key=lambda x: (x.get("level_required", 1), x.get("price", 0)))
selected_animal_id = str(best_animal.get("id"))
print(f" -> [Chốt] Mua loại cao nhất: {best_animal.get('name')} (ID: {selected_animal_id}) | Giá: {best_animal.get('price'):,} xu | Yêu cầu cấp: {best_animal.get('level_required')}")

# 5. THỰC HIỆN MUA VẬT NUÔI CHO TỪNG CHUỒNG
if selected_animal_id:
print("[5] MUA VẬT NUÔI: Tiến hành thả nuôi...")
for cage_idx in range(TOTAL_CAGES):
await safe_goto(page, "https://1900.fun/nongtrai/vatnuoi.php")
await page.wait_for_timeout(1000)

if await page.locator("#buyForm").count() > 0:
await page.evaluate(f"""() => {{
document.getElementById('buyCageIndex').value = '{cage_idx}';
document.getElementById('buyAnimalId').value = '{selected_animal_id}';
}}""")

async with page.expect_navigation(wait_until="domcontentloaded"):
await page.eval_on_selector("#buyForm", "form => form.submit()")

print(f" -> Đã mua thành công cho Chuồng {cage_idx + 1}")
await page.wait_for_timeout(1500)

# 6. ĐĂNG XUẤT
print("[6] Đăng xuất...")
await safe_goto(page, "https://1900.fun/logout.php")
await page.wait_for_timeout(1500)
print(f"[+] Hoàn tất cho: {username}")

except Exception as e:
print(f"[-] Có lỗi xảy ra đối với {username}: {e}")
finally:
await context.close()
await asyncio.sleep(2)

await browser.close()


if __name__ == "__main__":
while True:
try:
print(f"\n==================== [ BẮT ĐẦU VÒNG LẶP ĐIỂM DANH + VẬT NUÔI ] ====================")
asyncio.run(run_automation())
except Exception as err:
print(f"[!] Gặp lỗi ngoài dự kiến: {err}")

print(f"\n[⏳] Đã hoàn thành. Chờ 12 giờ ({INTERVAL_SECONDS}s) để chạy tiếp...")
time.sleep(INTERVAL_SECONDS)