import httpx
from .config import get_api_key_and_host

class CortifClient:
    def __init__(self):
        self.api_key, self.host = get_api_key_and_host()
        if not self.api_key or not self.host:
            raise ConnectionError("User not logged in. Please run 'cortif login'.")
        
        self.base_url = f"{self.host.rstrip('/')}/api"
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

    def get_projects(self):
        with httpx.Client(base_url=self.base_url, headers=self.headers) as client:
            try:
                response = client.get("/projects")
                response.raise_for_status()
                return response.json()
            except httpx.HTTPStatusError as e:
                print(f"Error fetching projects: {e.response.status_code} - {e.response.text}")
                return None
            except Exception as e:
                print(f"An error occurred: {e}")
                return None

    def get_project_details(self, project_id: str):
        with httpx.Client(base_url=self.base_url, headers=self.headers) as client:
            try:
                response = client.get(f"/projects/{project_id}")
                response.raise_for_status()
                return response.json()
            except httpx.HTTPStatusError:
                print(f"Error fetching project details for {project_id}: {response.status_code} - {response.text}")
                return None # Handled by caller

    def submit_run(self, payload: dict):
        with httpx.Client(base_url=self.base_url, headers=self.headers, timeout=30.0) as client:
            try:
                response = client.post("/runs/submit", json=payload)
                response.raise_for_status()
                return response.json()
            except httpx.HTTPStatusError as e:
                print(f"\nError submitting run: {e.response.status_code}")
                print(f"Response: {e.response.text}")
                return None
            except httpx.RequestError as e:
                print(f"\nConnection error: Failed to connect to {e.request.url}")
                return None