"""INFINN - Your first trade in 30 minutes (copy-paste script).

Flow: OAuth login -> access token -> UserDetails -> 1-share LMT BUY far below
the market -> OrderBook -> CancelOrder.

SAFE BY DEFAULT:
  * DRY_RUN = True  -> the order is only PRINTED, never sent.
  * Even with DRY_RUN = False you must type YES (capital letters) before the
    order is sent. Anything else skips the order.
  * Secrets are never printed in full (only the last 4 characters).
Practise first on Sandbox (UAT / Test — NOT live): https://uat.infinn.in. Then use live. A live sent order is a REAL order on your REAL account.
Requires Python 3.8+ and nothing else (standard library only).
"""
import hashlib, json, sys, time, urllib.parse, urllib.request, webbrowser

# ====================== FILL THESE 4-5 VALUES ======================
USER_ID      = "YOUR_USER_ID"       # e.g. the ID you use on trade.infinn.in
API_KEY      = "YOUR_API_KEY"       # "App Key" from the Generate Key panel
SECRET       = "YOUR_SECRET_CODE"   # "Secret Code" from the same panel
REDIRECT_URL = "https://example.com/callback"  # exactly as saved in the panel
SYMBOL       = "RELIANCE-EQ"            # optional: any liquid NSE cash symbol
# ===================================================================
DRY_RUN      = True                 # set to False only when you are ready
EXCHANGE     = "NSE"
PRICE_FACTOR = 0.5                  # limit price = 50% of last price (cannot fill)

LOGIN_URL = "https://api.infinn.in/OAuthlogin/investor-entry-level/login"
REST_BASE = "https://api.infinn.in/NorenWClientAPI/"

# Optional. Leave ORDER_SOURCE as None unless your broker has given you a value
# for the "ordersource" field (for example "API").
ORDER_SOURCE = None

TOKEN = None


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


def sha256(s):
    return hashlib.sha256(s.encode()).hexdigest()


def show(title, data):
    """Print a response with token-like fields masked."""
    def scrub(o):
        if isinstance(o, dict):
            return {k: (mask(v) if k in ("access_token", "refresh_token",
                    "susertoken", "checksum") else scrub(v)) for k, v in o.items()}
        if isinstance(o, list):
            return [scrub(x) for x in o]
        return o
    print(f"\n--- {title} ---")
    print(json.dumps(scrub(data), indent=2)[:3000])


def post(endpoint, payload, auth=True):
    """POST jData=<json> to the REST base, with 'Authorization: Bearer'."""
    body = "jData=" + urllib.parse.quote(json.dumps(payload, separators=(",", ":")))
    headers = {"Content-Type": "text/plain"}
    if auth:
        headers["Authorization"] = "Bearer " + TOKEN
    req = urllib.request.Request(REST_BASE + endpoint, data=body.encode(), headers=headers)
    with urllib.request.urlopen(req, timeout=20) as r:
        return json.loads(r.read().decode())


def code_from_text(text):
    """Return the RAW code (do NOT URL-decode it) from a pasted URL or code."""
    text = text.strip()
    if "code=" in text:
        for part in text.split("?", 1)[-1].split("&"):
            if part.startswith("code="):
                return part[5:]
    return text


def step_login():
    global TOKEN
    route_to = sha256(f"{USER_ID}|{SECRET}")          # lowercase hex
    url = f"{LOGIN_URL}?api_key={urllib.parse.quote(API_KEY)}&route_to={route_to}"
    print("STEP 1  Open this link, log in (password + TOTP):\n" + url)
    try:
        webbrowser.open(url)
    except Exception:
        pass
    print(f"After login the browser goes to {REDIRECT_URL}?code=...")
    code = code_from_text(input("Paste the FULL address-bar URL here and press Enter FAST: "))
    checksum = sha256(API_KEY + SECRET + code)       # raw code, not decoded
    res = post("GenAcsTok", {"code": code, "checksum": checksum}, auth=False)
    show("GenAcsTok", res)
    if res.get("stat") != "Ok":
        sys.exit("Login failed. Check: IP whitelisted? code used within seconds? "
                 "key/secret correct? code pasted without decoding?")
    TOKEN = res.get("access_token") or res.get("susertoken")
    print("Token received:", mask(TOKEN))


def far_price():
    s = post("SearchScrip", {"uid": USER_ID, "exch": EXCHANGE, "stext": SYMBOL})
    vals = s.get("values") or []
    hit = next((v for v in vals if v.get("tsym") == SYMBOL), vals[0] if vals else None)
    if not hit:
        sys.exit(f"Symbol {SYMBOL} not found on {EXCHANGE}.")
    q = post("GetQuotes", {"uid": USER_ID, "exch": EXCHANGE, "token": hit["token"]})
    lp = float(q.get("lp") or 0)
    if lp <= 0:
        sys.exit("Could not read the last price; not placing anything.")
    tick = float(q.get("ti") or 0.05)
    prc = max(tick, round(round(lp * PRICE_FACTOR / tick) * tick, 2))
    print(f"Last price {lp} -> safe limit price {prc} (far below market)")
    return hit["tsym"], prc


def main():
    step_login()
    ud = post("UserDetails", {"uid": USER_ID})
    show("UserDetails", ud)
    if ud.get("stat") != "Ok":
        sys.exit("UserDetails failed.")

    tsym, prc = far_price()
    order = {"uid": USER_ID, "actid": USER_ID, "exch": EXCHANGE, "tsym": tsym,
             "qty": "1", "prc": str(prc), "prd": "C", "trantype": "B",
             "prctyp": "LMT", "ret": "DAY", "remarks": "first-trade-test"}
    if ORDER_SOURCE:
        order["ordersource"] = ORDER_SOURCE
    show("Order that WOULD be sent", order)
    if DRY_RUN:
        print("\nDRY_RUN = True -> nothing sent. Set DRY_RUN = False to place it.")
        return
    if input("Type YES to send this REAL order (anything else cancels): ").strip() != "YES":
        print("Not sent.")
        return
    po = post("PlaceOrder", order)
    show("PlaceOrder", po)
    ordno = po.get("norenordno")
    if not ordno:
        sys.exit("No norenordno - order not accepted.")
    time.sleep(1)
    try:
        book = post("OrderBook", {"uid": USER_ID})
        mine = [r for r in book if isinstance(r, dict) and r.get("norenordno") == ordno] \
            if isinstance(book, list) else book
        show("OrderBook (this order)", mine)
    finally:
        show("CancelOrder", post("CancelOrder", {"uid": USER_ID, "norenordno": ordno}))
        time.sleep(1)
        book = post("OrderBook", {"uid": USER_ID})
        if isinstance(book, list):
            st = [r.get("status") for r in book if r.get("norenordno") == ordno]
            print("Final status:", st[0] if st else "unknown")


if __name__ == "__main__":
    main()
