import time
import requests
from bs4 import BeautifulSoup
import ctypes
import sys

# --- Ẩn cửa sổ CMD ngay khi chạy ---
def hide_console():
try:
# Lấy handle của cửa sổ console hiện tại
hwnd = ctypes.windll.kernel32.GetConsoleWindow()
if hwnd:
# 0 = SW_HIDE (Ẩn cửa sổ)
ctypes.windll.user32.ShowWindow(hwnd, 0)
except Exception:
pass

# Gọi ẩn console ngay khi chương trình khởi chạy
hide_console()

# ================== CẤU HÌNH ==================
LOGIN_URL = "https://1900.fun/login.php"
CITY_URL = "https://1900.fun/city/"
PK_AJAX_URL = "https://1900.fun/city/ajax_pk.php"

USERNAME = "hoangchan2"
PASSWORD = "abc13579"

# Ngưỡng HP mục tiêu nâng lên 8000 HP
MAX_TARGET_HP = 8000
INTERVAL_SECONDS = 2 * 60 * 60 # Nghỉ 2 giờ giữa các vòng
# ==============================================


def run_bot():
session = requests.Session()
session.headers.update(
{
"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",
"X-Requested-With": "XMLHttpRequest",
}
)

# 1. Đăng nhập
print(f"[*] Đang đăng nhập tài khoản: {USERNAME}...")
login_payload = {"username": USERNAME, "password": PASSWORD}
session.post(LOGIN_URL, data=login_payload)

# 2. Tải trang Thành phố & phân tích DOM
print("[*] Đang tải danh sách người chơi trong Thành phố...")
res_city = session.get(CITY_URL)
soup = BeautifulSoup(res_city.text, "html.parser")
house_cards = soup.find_all("div", class_="house-card")

targets = []
for card in house_cards:
onclick_attr = card.get("onclick", "")
if "openPK(" in onclick_attr:
try:
param_str = onclick_attr.split("openPK(")[1].split(")")[0]
params = [p.strip().strip("'\"") for p in param_str.split(",")]
user_id = int(params[0])
name = params[1]
hp = int(params[2])
strength = int(params[3])

# Kiểm tra điều kiện HP dưới ngưỡng MAX_TARGET_HP (8000)
if hp < MAX_TARGET_HP:
targets.append(
{
"id": user_id,
"name": name,
"hp": hp,
"strength": strength,
}
)
except Exception:
continue

print(f"[+] Tìm thấy {len(targets)} mục tiêu có HP < {MAX_TARGET_HP}:\n")
for target in targets:
print(f" - {target['name']} (ID: {target['id']}) | HP: {target['hp']}")

print("\n[*] Bắt đầu tiến hành chiến đấu...")

# 3. Thực hiện gửi yêu cầu PK
for target in targets:
print(f"⚔️ Đang tấn công: {target['name']} (ID: {target['id']}) - HP: {target['hp']}...")
pk_data = {
"action": "end_battle",
"target_id": target["id"],
"result": "win",
}
try:
response = session.post(PK_AJAX_URL, data=pk_data)
res_json = response.json()
if res_json.get("success"):
print(f" └─ SUCCESS: {res_json.get('message', 'Thành công')}")
if "new_xu" in res_json:
print(f" └─ Số dư mới: {res_json['new_xu']} Xu")
else:
print(f" └─ FAILED: {res_json.get('message', 'Thất bại/Bị chặn')}")
except Exception as e:
print(f" └─ ERROR: Không thể kết nối hoặc lỗi dữ liệu ({e})")

time.sleep(3.5)


if __name__ == "__main__":
while True:
try:
print(f"\n==================== [ BẮT ĐẦU VÒNG LẶP PK ] ====================")
run_bot()
except Exception as err:
print(f"[!] Gặp lỗi ngoài dự kiến: {err}")

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