"""
Cin7 API client — fetch Products, Categories, Brands, Contacts
Cin7 API uses pagination: ?page=1&rows=250, response: {d: [...], pageCount: N}
Rate limit: 3 calls/sec, 60/min, 5000/day
"""
import requests
from requests.auth import HTTPBasicAuth
import time
from config import CIN7_BASE_URL, CIN7_USERNAME, CIN7_PASSWORD


class Cin7Api:

    def __init__(self):
        self.auth = HTTPBasicAuth(CIN7_USERNAME, CIN7_PASSWORD)
        self.session = requests.Session()
        self.session.auth = self.auth

    def _get(self, endpoint, params=None):
        url = f"{CIN7_BASE_URL.rstrip('/')}/{endpoint.lstrip('/')}"
        resp = self.session.get(url, params=params, timeout=30)
        if resp.status_code == 404:
            return {}
        resp.raise_for_status()
        return resp.json()

    def _get_pages(self, endpoint, page=1, rows=250):
        """Fetch all records across multiple pages"""
        all_items = []
        while True:
            params = {"page": page, "rows": rows}
            data = self._get(endpoint, params)
            if isinstance(data, dict):
                items = data.get("d", []) if data else []
            elif isinstance(data, list):
                items = data
            else:
                items = []
            if not items:
                break
            all_items.extend(items)
            # If less than rows returned, we've reached the last page
            if len(items) < rows:
                break
            page += 1
            # Cin7 rate limit: 3 calls/sec, sleep to avoid 429
            time.sleep(0.4)
        return all_items

    def get_products(self, modified_since=None):
        """Fetch all products (paginated)"""
        return self._get_pages("v1/Products", page=1, rows=250)

    def get_categories(self):
        """Fetch all product categories (paginated)"""
        return self._get_pages("v1/ProductCategories", page=1, rows=250)

    def get_brands(self):
        """Fetch all Cin7 Branches as brands (paginated)"""
        return self._get_pages("v1/Branches", page=1, rows=250)

    def get_contacts(self, contact_type=None):
        """Fetch contacts, optionally filtered by type (Customer/Supplier)"""
        all_contacts = self._get_pages("v1/Contacts", page=1, rows=250)
        print(f"[DEBUG] get_contacts: total fetched={len(all_contacts)}, filter={contact_type}")
        if all_contacts:
            print(f"[DEBUG] first contact type={all_contacts[0].get('type')}")
        if contact_type:
            return [c for c in all_contacts if str(c.get("type", "")) == contact_type]
        return all_contacts

    def test_connection(self):
        """Verify API credentials work"""
        try:
            self.get_products()
            return True
        except Exception as e:
            print(f"[Cin7] Connection failed: {e}")
            return False
