import os
import requests
import json
from typing import Dict, Any, Optional

class InstantlyClientV2:
    """
    Genesis Instantly AI V2 API Client.
    Specialized for autonomous ingestion and campaign governance.
    """
    
    BASE_URL = "https://api.instantly.ai/v2"

    def __init__(self, api_key: Optional[str] = None):
        self.api_key = api_key or os.environ.get("INSTANTLY_API_KEY")
        if not self.api_key:
            raise ValueError("INSTANTLY_API_KEY must be provided or set in environment.")

    def _get_headers(self) -> Dict[str, str]:
        return {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

    def list_accounts(self) -> Dict[str, Any]:
        """Verify connectivity by listing sending accounts."""
        response = requests.get(f"{self.BASE_URL}/accounts", headers=self._get_headers())
        response.raise_for_status()
        return response.json()

    def get_campaigns(self, limit: int = 10) -> Dict[str, Any]:
        """List campaigns for synchronization with Genesis."""
        response = requests.get(f"{self.BASE_URL}/campaigns?limit={limit}", headers=self._get_headers())
        response.raise_for_status()
        return response.json()

    def create_campaign(self, name: str) -> Dict[str, Any]:
        """Create a new outreach campaign (The Receptionist Wedge)."""
        payload = {"name": name}
        response = requests.post(f"{self.BASE_URL}/campaigns", headers=self._get_headers(), data=json.dumps(payload))
        response.raise_for_status()
        return response.json()

    def add_lead(self, campaign_id: str, email: str, variables: Dict[str, str]) -> Dict[str, Any]:
        """Inject leads into a specific campaign."""
        payload = {
            "leads": [
                {
                    "email": email,
                    "variables": variables
                }
            ]
        }
        response = requests.post(f"{self.BASE_URL}/campaigns/{campaign_id}/leads", headers=self._get_headers(), data=json.dumps(payload))
        response.raise_for_status()
        return response.json()

if __name__ == "__main__":
    # Internal validation block
    print("InstantlyClientV2 Initialized.")
