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 # 1 phú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(1000)
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(1200)

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:
Thương Hoàng Kim + Đang dùng
"""
name = name_text.lower()
if "thương hoàng kim" not in name and "thuong hoang kim" not in name:
return False
if not has_equipped:
return False
return True


async def sell_unwanted_weapons(page) -> int:
"""
Bán tất cả vũ khí, chỉ giữ Thương Hoàng Kim đang dùng (+10).
Dùng điều hướng ?sell=ID để bỏ qua hộp thoại confirm.
"""
sold_count = 0
max_rounds = 60

for round_idx in range(max_rounds):
await page.goto(INVENTORY_URL, wait_until="domcontentloaded", timeout=30000)
await page.wait_for_timeout(1200)

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

sell_id = None
sell_name = None

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 ""

if is_keep_weapon(name_text, has_equipped, enhance_text, damage_text):
short = name_text.replace("\n", " ")[:50]
print(f" [GIỮ] {short} | {enhance_text} | {damage_text[:40]}")
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 not m:
continue

sell_id = m.group(1)
sell_name = name_text.splitlines()[0].strip()[:40]
break

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

if not sell_id:
print("[*] Không còn món nào cần bán.")
break

print(f" → Đang bán: {sell_name} (ID: {sell_id})")
try:
await page.goto(
f"{INVENTORY_URL}?sell={sell_id}",
wait_until="domcontentloaded",
timeout=20000,
)
sold_count += 1
await page.wait_for_timeout(700)
except Exception as e:
print(f" [!] Lỗi bán ID {sell_id}: {e}")
break

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("[*] Vào túi đồ — bán hết, chỉ giữ Thương Hoàng Kim đang dùng (+10)...")
sold = await sell_unwanted_weapons(page)
print(f"[✓] Đã bán {sold} món.")
print("[✓] Chỉ giữ lại: Thương Hoàng Kim (Đang dùng, Rèn +10, ST +146)")

except Exception as e:
print(f"[!] Lỗi: {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 ngoài: {e}")

print(f"\n[⏳] Nghỉ {INTERVAL_SECONDS // 60} phút rồi chạy lại...")
await asyncio.sleep(INTERVAL_SECONDS)
cycle += 1


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