import asyncio
import ctypes
import re
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 ==================
USERNAME = "hoangchan2"
PASSWORD = "abc13579"
LOGIN_URL = "https://1900.fun/login.php"
INVENTORY_URL = "https://1900.fun/city/inventory.php"

INTERVAL_SECONDS = 1 * 60 # Nghỉ 1 phút giữa các vòng quét
HEADLESS = True
# ==============================================


async def login(page, username: str, password: str) -> bool:
try:
await page.goto(LOGIN_URL, wait_until="domcontentloaded", timeout=30000)
await page.wait_for_timeout(500)
await page.fill("input[name='username']", username)
await page.fill("input[name='password']", password)
async with page.expect_navigation(wait_until="domcontentloaded", timeout=15000):
await page.click("button[type='submit']")
await page.wait_for_timeout(800)

content = (await page.content()).lower()
url = page.url.lower()
if "login" in url and "logout" not in content:
return False
return True
except Exception as e:
print(f"[!] Lỗi đăng nhập: {e}")
return False


def is_keep_weapon(name_text: str, has_equipped: bool, enhance_text: str, damage_text: str) -> bool:
"""
Chỉ giữ lại duy nhất:
Thương Hoàng Kim + Đang dùng + Rèn +10 + Sát thương +146
"""
name = name_text.lower()

# Check 1: Tên phải là Thương Hoàng Kim
if "thương hoàng kim" not in name and "thuong hoang kim" not in name:
return False

# Check 2: Phải đang trang bị
if not has_equipped:
return False

# Check 3: Cường hóa / Rèn +10
if "+10" not in enhance_text and "+10" not in name_text:
return False

# Check 4: Sát thương +146
if "146" not in damage_text and "146" not in name_text:
return False

return True


async def sell_unwanted_weapons(page) -> int:
"""
Quét danh sách túi đồ và bán sạch mọi vũ khí không thuộc điều kiện giữ.
"""
sold_count = 0

while True:
await page.goto(INVENTORY_URL, wait_until="domcontentloaded", timeout=30000)
await page.wait_for_timeout(1000)

items = await page.query_selector_all(".weapon-item")
if not items:
print("[*] Không tìm thấy vũ khí nào trong túi đồ.")
break

to_sell_list = []

# Bước 1: Quét nhanh toàn bộ trang để gom ID cần bán
for item in items:
try:
name_el = await item.query_selector(".weapon-name")
if not name_el:
continue
name_text = (await name_el.inner_text()).strip()

equipped_el = await item.query_selector(".equipped-badge")
has_equipped = equipped_el is not None

enhance_el = await item.query_selector(".enhance-badge")
enhance_text = (await enhance_el.inner_text()).strip() if enhance_el else ""

damage_el = await item.query_selector(".weapon-damage")
damage_text = (await damage_el.inner_text()).strip() if damage_el else ""

# Kiểm tra nếu đúng vũ khí VIP cần giữ
if is_keep_weapon(name_text, has_equipped, enhance_text, damage_text):
short_info = name_text.replace("\n", " ")[:60]
print(f" [🔒 GIỮ] {short_info} | {enhance_text} | {damage_text[:30]}")
continue

sell_btn = await item.query_selector("a.sell-btn")
if not sell_btn:
continue

href = await sell_btn.get_attribute("href") or ""
m = re.search(r"sell=(\d+)", href)
if m:
sell_id = m.group(1)
clean_name = name_text.splitlines()[0].strip()[:30]
to_sell_list.append((sell_id, clean_name))

except Exception as e:
print(f" [!] Lỗi đọc item: {e}")
continue

# Nếu không còn món nào cần bán thì dừng loop
if not to_sell_list:
print("[*] Đã dọn dẹp xong! Không còn vũ khí rác nào.")
break

print(f"[*] Tìm thấy {len(to_sell_list)} vũ khí cần bán trong đợt này. Bắt đầu bán...")

# Bước 2: Bán lần lượt từng ID tìm được
for sell_id, item_name in to_sell_list:
try:
sold_count += 1
print(f" → [{sold_count}] Đang bán: {item_name} (ID: {sell_id})")
await page.goto(
f"{INVENTORY_URL}?sell={sell_id}",
wait_until="domcontentloaded",
timeout=15000,
)
await page.wait_for_timeout(300) # Nghỉ nhẹ 0.3s để tránh bị server chặn spam
except Exception as e:
print(f" [!] Lỗi bán ID {sell_id}: {e}")

return sold_count


async def run_once():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=HEADLESS)
context = await 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 = await context.new_page()
page.set_default_timeout(30000)

try:
print(f"[*] Đăng nhập: {USERNAME}")
ok = await login(page, USERNAME, PASSWORD)
if not ok:
print("[!] Đăng nhập thất bại")
return

print("[*] Đang tiến hành quét túi đồ và bán sạch vũ khí rác...")
sold = await sell_unwanted_weapons(page)
print(f"[✓] Tổng cộng đã bán: {sold} món.")
print("[✓] An toàn: Thương Hoàng Kim (Đang dùng | +10 | ST +146) vẫn được giữ lại.")

except Exception as e:
print(f"[!] Lỗi trong quá trình chạy: {e}")
finally:
await browser.close()


async def main():
cycle = 1
while True:
print("\n" + "=" * 55)
print(f" AUTO BÁN ĐỒ — VÒNG {cycle}")
print("=" * 55)
try:
await run_once()
except Exception as e:
print(f"[!] Lỗi hệ thống: {e}")

print(f"\n[⏳] Nghỉ {INTERVAL_SECONDS // 60} phút rồi tiếp tục quét...")
await asyncio.sleep(INTERVAL_SECONDS)
cycle += 1


if __name__ == "__main__":
asyncio.run(main())