"""
AkDevz AI Market Intelligence — FYERS OAuth & Token Manager
Handles SHA-256 appIdHash generation and token lifecycle management.
"""
import hashlib
import httpx
from typing import Dict, Any
from python.config.settings import settings

class FyersAuth:
    BASE_URL = "https://api-t1.fyers.in"

    def __init__(self, app_id: str = "", secret_key: str = "", redirect_uri: str = ""):
        self.app_id = app_id or settings.fyers_app_id
        self.secret_key = secret_key or settings.fyers_secret_key
        self.redirect_uri = redirect_uri or settings.fyers_redirect_uri

    def compute_app_id_hash(self) -> str:
        raw = f"{self.app_id}:{self.secret_key}"
        return hashlib.sha256(raw.encode("utf-8")).hexdigest()

    def get_auth_url(self, state: str = "akdevz_login") -> str:
        return (
            f"{self.BASE_URL}/api/v3/generate-authcode"
            f"?client_id={self.app_id}"
            f"&redirect_uri={self.redirect_uri}"
            f"&response_type=code"
            f"&state={state}"
        )

    def exchange_code_for_token(self, auth_code: str) -> Dict[str, Any]:
        url = f"{self.BASE_URL}/api/v3/validate-authcode"
        app_id_hash = self.compute_app_id_hash()

        payload = {
            "grant_type": "authorization_code",
            "appIdHash": app_id_hash,
            "code": auth_code,
        }

        with httpx.Client(timeout=15.0) as client:
            resp = client.post(url, json=payload)
            if resp.status_code != 200:
                raise RuntimeError(
                    f"FYERS Auth Failed (HTTP {resp.status_code}): {resp.text}"
                )
            data = resp.json()
            if "access_token" not in data:
                raise RuntimeError(f"No access token in FYERS response: {data}")

            return {
                "status": "success",
                "access_token": data["access_token"],
                "raw": data
            }
