import os
import sys
import json
import logging
import requests
from dotenv import load_dotenv

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger("list_products")

# --- Inline AuthHandler & SuperOfficeClient (Proven Working Logic) ---

class AuthHandler:
    def __init__(self):
        # CRITICAL: override=True ensures we read from .env even if env vars are already set
        load_dotenv(override=True)
        
        self.client_id = os.getenv("SO_CLIENT_ID") or os.getenv("SO_SOD")
        self.client_secret = os.getenv("SO_CLIENT_SECRET")
        self.refresh_token = os.getenv("SO_REFRESH_TOKEN")
        self.redirect_uri = os.getenv("SO_REDIRECT_URI", "http://localhost")
        self.env = os.getenv("SO_ENVIRONMENT", "sod")
        self.cust_id = os.getenv("SO_CONTEXT_IDENTIFIER", "Cust55774")

        if not all([self.client_id, self.client_secret, self.refresh_token]):
            raise ValueError("SuperOffice credentials missing in .env file.")

    def get_access_token(self):
        return self._refresh_access_token()

    def _refresh_access_token(self):
        token_domain = "online.superoffice.com" if "online" in self.env.lower() else "sod.superoffice.com"
        url = f"https://{token_domain}/login/common/oauth/tokens"
        
        data = {
            "grant_type": "refresh_token",
            "client_id": self.client_id,
            "client_secret": self.client_secret,
            "refresh_token": self.refresh_token,
            "redirect_uri": self.redirect_uri
        }
        try:
            resp = requests.post(url, data=data)
            if resp.status_code != 200:
                logger.error(f"❌ Token Refresh Failed (Status {resp.status_code}): {resp.text}")
                return None
            return resp.json().get("access_token")
        except Exception as e:
            logger.error(f"❌ Connection Error during token refresh: {e}")
            return None

class SuperOfficeClient:
    def __init__(self, auth_handler):
        self.auth_handler = auth_handler
        self.env = auth_handler.env
        self.cust_id = auth_handler.cust_id
        self.base_url = f"https://{self.env}.superoffice.com/{self.cust_id}/api/v1"
        self.access_token = self.auth_handler.get_access_token()
        
        if not self.access_token:
            raise Exception("Failed to obtain access token.")
        
        self.headers = {
            "Authorization": f"Bearer {self.access_token}",
            "Content-Type": "application/json",
            "Accept": "application/json"
        }

    def _get(self, endpoint):
        url = f"{self.base_url}/{endpoint}"
        logger.info(f"Attempting to GET: {url}")
        resp = requests.get(url, headers=self.headers)
        resp.raise_for_status()
        return resp.json()

def main():
    try:
        # Initialize Auth and Client
        auth = AuthHandler()
        client = SuperOfficeClient(auth)
        
        print("\n--- 1. Fetching Product Information ---")
        
        product_families = []
        endpoint_to_try = "List/ProductFamily/Items"

        try:
            product_families = client._get(endpoint_to_try)
        except requests.exceptions.HTTPError as e:
            logger.error(f"Failed to fetch from '{endpoint_to_try}': {e}")
            print(f"Could not find Product Families at '{endpoint_to_try}'. This might not be the correct endpoint or list name.")
            # If the first endpoint fails, you could try others here.
            # For now, we will exit if this one fails.
            return

        if not product_families:
            print("No product families found or the endpoint returned an empty list.")
            return

        print("\n--- ✅ SUCCESS: Found Product Families ---")
        print("-----------------------------------------")
        print(f"{'ID':<10} | {'Name':<30} | {'Tooltip':<40}")
        print("-----------------------------------------")
        
        for product in product_families:
            product_id = product.get('Id', 'N/A')
            name = product.get('Name', 'N/A')
            tooltip = product.get('Tooltip', 'N/A')
            print(f"{str(product_id):<10} | {name:<30} | {tooltip:<40}")
        
        print("-----------------------------------------")

    except requests.exceptions.HTTPError as e:
        logger.error(f"❌ API Error: {e}")
        if e.response is not None:
             logger.error(f"Response Body: {e.response.text}")
    except Exception as e:
        logger.error(f"Fatal Error: {e}")

if __name__ == "__main__":
    main()
