# -*- coding: utf-8 -*-
"""Kiểm cơ chế đăng nhập /lab qua URL công khai: POST mật khẩu trong mat_khau.txt rồi GET trang chính."""
import http.cookiejar, os, re, urllib.error, urllib.parse, urllib.request

GOC = r'C:\Claw 2\Nghien cuu\Agent-Lab'
mk = open(os.path.join(GOC, 'mat_khau.txt'), encoding='utf-8').read().strip()
print('mật khẩu trong mat_khau.txt: %r (dài %d ký tự)' % (mk, len(mk)))
PUB = 'https://desktop-9gsdkd2.tail0ffe94.ts.net/lab/'

cj = http.cookiejar.CookieJar()
o = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
o.addheaders = [('User-Agent', 'Mozilla/5.0')]

# 1. trang đăng nhập
r = o.open(PUB, timeout=20)
print('GET /lab/ →', r.status, '| cookie trước khi đăng nhập:', len(cj))

# 2. POST mật khẩu
try:
    r2 = o.open(PUB + 'dang-nhap', urllib.parse.urlencode({'mat_khau': mk}).encode(), timeout=25)
    print('POST /lab/dang-nhap →', r2.status, '| url cuối:', r2.url)
except urllib.error.HTTPError as e:
    print('POST lỗi HTTP', e.code, e.reason)
    r2 = None

print('cookie sau đăng nhập:', [(c.name, c.value[:10] + '…', c.path) for c in cj])

# 3. GET trang chính xem đã vào được chưa
h = o.open(PUB, timeout=20).read().decode('utf-8')
print('trang chính:', len(h), 'byte | còn form đăng nhập:', 'name="mat_khau"' in h,
      '| có form tạo việc:', 'name="loai_go"' in h or 'Gửi cho AGY' in h)

# 4. so với mật khẩu CALIB (kiểm anh có lẫn không)
mk_calib = open(r'C:\Claw 2\Nghien cuu\Du-an-B-He-mau-Stain-Glaze\calib-app\mat_khau.txt', encoding='utf-8').read().strip()
print('mật khẩu CALIB khác /lab?:', mk_calib != mk)
print('thử POST bằng mật khẩu CALIB:')
cj2 = http.cookiejar.CookieJar()
o2 = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj2))
try:
    r3 = o2.open(PUB + 'dang-nhap', urllib.parse.urlencode({'mat_khau': mk_calib}).encode(), timeout=25)
    h2 = o2.open(PUB, timeout=20).read().decode('utf-8')
    print('  → vào được bằng mật khẩu CALIB?', 'name="mat_khau"' not in h2)
except Exception as e:
    print('  → lỗi:', e)
