#!/usr/bin/env python3
"""infinn_quick_login.py -- log in to the INFINN API with no copy-paste.

What it does
  1. Asks for your user ID, API key and API secret (the secret is typed hidden).
  2. Opens the INFINN login page in your browser. You enter password + TOTP there.
  3. INFINN sends the browser back to http://127.0.0.1:8899/callback.
     This script catches the one-time code instantly and exchanges it for a token.
  4. Saves the token to infinn_token.json (only on this PC) and prints it masked.

Before the first run: set your Redirect URL to  http://127.0.0.1:8899/callback
in trade.infinn.in -> top-right profile icon -> Generate Key (API Key panel). Your static IP must be whitelisted there too.

Needs only Python 3.8+ (no extra packages). It never places orders.
"""
import getpass, hashlib, http.client, json, os, threading, urllib.parse, webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer

PORT = int(os.environ.get("INFINN_CALLBACK_PORT", "8899"))
BASE = os.environ.get("INFINN_BASE", "https://api.infinn.in")
LOGIN = os.environ.get("INFINN_LOGIN_URL", "https://api.infinn.in/OAuthlogin/investor-entry-level/login")
TOKEN_FILE = os.environ.get("INFINN_TOKEN_FILE", "infinn_token.json")

def mask(v):
    s = str(v or "")
    return "****" + s[-4:] if s else "(none)"

def route_to(user_id, secret):
    # Recipe used by working INFINN clients: SHA-256 of "USERID|SECRET", lower-case hex.
    return hashlib.sha256((user_id + "|" + secret).encode("utf-8")).hexdigest()

def checksum(api_key, secret, code):
    return hashlib.sha256((api_key + secret + code).encode("utf-8")).hexdigest()

def gen_acs_tok(api_key, secret, code):
    body = "jData=" + json.dumps({"code": code, "checksum": checksum(api_key, secret, code)}, separators=(",", ":"))
    u = urllib.parse.urlparse(BASE.rstrip("/") + "/NorenWClientAPI/GenAcsTok")
    cls = http.client.HTTPSConnection if u.scheme == "https" else http.client.HTTPConnection
    conn = cls(u.netloc, timeout=10)
    try:
        conn.request("POST", u.path, body=body.encode("utf-8"),
                     headers={"Content-Type": "application/x-www-form-urlencoded"})
        r = conn.getresponse()
        text = r.read().decode("utf-8", "replace")
        status = r.status
    finally:
        conn.close()
    try:
        return status, json.loads(text) if text.strip() else {}
    except ValueError:
        return status, {}

class Catch(BaseHTTPRequestHandler):
    code = None
    def log_message(self, *a):
        pass
    def do_GET(self):
        q = urllib.parse.urlparse(self.path).query
        if self.path.startswith("/callback") and "code=" in q:
            Catch.code = q.split("code=", 1)[1].split("&", 1)[0]   # raw, not URL-decoded
            msg = "Login code received. You can close this tab and go back to the black window."
        else:
            msg = "Waiting for the INFINN login..."
        b = ("<html><body style='font-family:Arial;padding:40px'><h2>%s</h2></body></html>" % msg).encode()
        self.send_response(200); self.send_header("Content-Type", "text/html"); self.send_header("Content-Length", str(len(b)))
        self.end_headers(); self.wfile.write(b)

def main():
    print("INFINN quick login (no orders are placed)\n")
    user = (os.environ.get("INFINN_USER_ID") or input("User ID: ")).strip().upper()
    key = (os.environ.get("INFINN_API_KEY") or input("API key: ")).strip()
    secret = (os.environ.get("INFINN_SECRET_KEY") or getpass.getpass("API secret (hidden): ")).strip()
    srv = HTTPServer(("127.0.0.1", PORT), Catch)
    srv.timeout = 1
    url = LOGIN + "?" + urllib.parse.urlencode({"api_key": key, "route_to": route_to(user, secret)})
    print("\nOpening the INFINN login page. Enter your password and TOTP there.")
    print("If it does not open, paste this into your browser:\n" + url + "\n")
    if not os.environ.get("INFINN_NO_BROWSER"):
        threading.Timer(0.5, lambda: webbrowser.open(url)).start()
    try:
        for _ in range(300):                 # wait up to about 5 minutes
            srv.handle_request()
            if Catch.code:
                break
    finally:
        srv.server_close()
    if not Catch.code:
        raise SystemExit("No login code arrived. Is your Redirect URL set to http://127.0.0.1:%d/callback ?" % PORT)
    status, data = gen_acs_tok(key, secret, Catch.code)
    secret = None
    if status != 200 or data.get("stat") != "Ok" or not data.get("access_token"):
        print("Login FAILED: HTTP %s, stat=%s, emsg=%s" % (status, data.get("stat"), data.get("emsg", "")))
        print("First check: is THIS computer's public IP whitelisted in the API Key panel?")
        print("Then: is the API key/secret correct? Try again (each login code works once, for a few seconds).")
        raise SystemExit(1)
    saved = {"uid": data.get("uid") or data.get("USERID"), "actid": data.get("actid"),
             "access_token": data["access_token"], "expires_in": data.get("expires_in")}
    with open(TOKEN_FILE, "w", encoding="utf-8") as fh:
        json.dump(saved, fh, indent=2)
    try:
        os.chmod(TOKEN_FILE, 0o600)
    except OSError:
        pass
    print("Login OK. user=%s actid=%s token=%s" % (mask(saved["uid"]), mask(saved["actid"]), mask(saved["access_token"])))
    print("Token saved to %s (keep it private). It works until about 4:00 AM IST." % TOKEN_FILE)
    print("Use it as the header:  Authorization: Bearer <access_token>")

if __name__ == "__main__":
    main()
