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95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
"""
Supervisor API Client.

A client for interacting with the HR Supervisor Agent API.
Supports both regular and streaming responses.

=============================================================================
AVAILABLE METHODS:
=============================================================================

WITH CONTEXT ENGINEERING (CompactingSupervisor wrapper):
    - chat()    : Batch response with automatic context compaction
    - stream()  : Streaming response with context compaction [HAS ERRORS - TODO FIX]

RAW SUPERVISOR (Direct agent access, no wrapper):
    - chat_raw()    : Batch response, direct supervisor agent
    - stream_raw()  : Streaming response, direct supervisor agent [HAS ERRORS - TODO FIX]

=============================================================================
NOTE: Both streaming methods (stream() and stream_raw()) have known issues 
that need to be fixed. Use batch methods (chat, chat_raw) for reliable operation.
=============================================================================
"""

import os
import json
from dataclasses import dataclass
from typing import Generator, Optional
import requests


def _clean_base_url(url: str) -> str:
    """Normalize base URL to avoid issues from quoted env vars."""
    cleaned = url.strip().strip("\"'")
    if cleaned.endswith("/"):
        cleaned = cleaned[:-1]
    return cleaned


@dataclass
class ChatResponse:
    """Response from a chat request."""
    content: str
    thread_id: str
    token_count: int


@dataclass
class StreamChunk:
    """A chunk from a streaming response."""
    type: str  # 'token', 'done', or 'error'
    content: Optional[str] = None
    thread_id: Optional[str] = None
    token_count: Optional[int] = None
    error: Optional[str] = None


class SupervisorClient:
    """
    Client for the HR Supervisor Agent API.
    
    Two categories of methods:
    
    1. WITH CONTEXT ENGINEERING (uses CompactingSupervisor wrapper):
       - chat()   : Batch request with automatic context compaction
       - stream() : Streaming with context compaction [HAS ERRORS - TODO FIX]
       
    2. RAW SUPERVISOR (direct agent access, no wrapper):
       - chat_raw()   : Batch request, direct supervisor agent
       - stream_raw() : Streaming, direct supervisor agent [HAS ERRORS - TODO FIX]
    
    ⚠️ NOTE: Both streaming methods have issues. Use batch methods for reliable operation.
    
    Usage:
        client = SupervisorClient()
        
        # Batch chat with context engineering (RECOMMENDED)
        response = client.chat("Show me all candidates")
        print(response.content)
        
        # Batch chat without wrapper (RECOMMENDED)
        response = client.chat_raw("Show me all candidates")
        print(response.content)
        
        # With conversation continuity
        response1 = client.chat("Show me all candidates", thread_id="abc123")
        response2 = client.chat("Tell me more about the first one", thread_id="abc123")
    """
    
    def __init__(self, base_url: Optional[str] = None, session_id: Optional[str] = None):
        """
        Initialize the Supervisor client.
        
        Args:
            base_url: API base URL. Defaults to SUPERVISOR_API_URL env var
                      or http://localhost:8080/api/v1/supervisor
        """
        raw = base_url or os.getenv(
            "SUPERVISOR_API_URL", 
            "http://localhost:8080/api/v1/supervisor"
        )
        self.base_url = _clean_base_url(raw)
        self.session_id = (session_id or os.getenv("SESSION_ID") or "").strip().strip("\"'")

    def _headers(self) -> dict:
        """Build headers including session isolation id."""
        headers = {}
        if self.session_id:
            headers["X-Session-Id"] = self.session_id
        return headers
    
    # =========================================================================
    # CONTEXT ENGINEERING METHODS (with CompactingSupervisor wrapper)
    # =========================================================================
    
    def chat(self, message: str, thread_id: Optional[str] = None, timeout: int = 120) -> ChatResponse:
        """
        Send a message and get a complete response.
        
        Uses CompactingSupervisor wrapper for automatic context management.
        When token limit is exceeded, old messages are compacted/summarized.
        
        Args:
            message: The message to send
            thread_id: Optional thread ID for conversation continuity
            timeout: Request timeout in seconds
            
        Returns:
            ChatResponse with content, thread_id, and token_count
            
        Raises:
            requests.exceptions.RequestException: On connection errors
            ValueError: On API errors
        """
        payload = {"message": message, "thread_id": thread_id}
        
        response = requests.post(
            f"{self.base_url}/chat",
            json=payload,
            headers=self._headers(),
            timeout=timeout
        )
        
        if response.status_code != 200:
            error = response.json().get("detail", "Unknown error")
            raise ValueError(f"API error: {error}")
        
        data = response.json()
        return ChatResponse(
            content=data["response"],
            thread_id=data["thread_id"],
            token_count=data["token_count"]
        )
    
    def stream(
        self, 
        message: str, 
        thread_id: Optional[str] = None, 
        timeout: int = 300
    ) -> Generator[StreamChunk, None, None]:
        """
        Send a message and stream the response token by token.
        
        ⚠️ WARNING: This method has known issues and needs to be fixed.
        Use stream_raw() for reliable streaming, or chat() for batch requests.
        
        Uses CompactingSupervisor wrapper for automatic context management.
        
        Args:
            message: The message to send
            thread_id: Optional thread ID for conversation continuity
            timeout: Request timeout in seconds
            
        Yields:
            StreamChunk objects with type 'token', 'done', or 'error'
            
        Example:
            full_response = ""
            for chunk in client.stream("Hello"):
                if chunk.type == "token":
                    full_response += chunk.content
                    print(chunk.content, end="", flush=True)
                elif chunk.type == "done":
                    print(f"\\nThread: {chunk.thread_id}")
                elif chunk.type == "error":
                    print(f"Error: {chunk.error}")
        """
        payload = {"message": message, "thread_id": thread_id}
        
        try:
            with requests.post(
                f"{self.base_url}/chat/stream",
                json=payload,
                headers=self._headers(),
                stream=True,
                timeout=timeout
            ) as response:
                if response.status_code != 200:
                    yield StreamChunk(
                        type="error",
                        error=f"API returned status {response.status_code}"
                    )
                    return
                
                current_event = None
                for line in response.iter_lines(decode_unicode=True):
                    if not line:
                        continue
                    
                    if line.startswith("event:"):
                        current_event = line[6:].strip()
                    elif line.startswith("data:") and current_event:
                        try:
                            data = json.loads(line[5:].strip())
                            
                            if current_event == "token":
                                yield StreamChunk(
                                    type="token",
                                    content=data.get("content", "")
                                )
                            elif current_event == "done":
                                yield StreamChunk(
                                    type="done",
                                    thread_id=data.get("thread_id"),
                                    token_count=data.get("token_count", 0)
                                )
                            elif current_event == "error":
                                yield StreamChunk(
                                    type="error",
                                    error=data.get("error", "Unknown error")
                                )
                        except json.JSONDecodeError:
                            continue
                        current_event = None
                        
        except requests.exceptions.ConnectionError:
            yield StreamChunk(
                type="error",
                error="Cannot connect to API. Make sure the server is running."
            )
        except requests.exceptions.Timeout:
            yield StreamChunk(type="error", error="Request timed out.")
        except Exception as e:
            yield StreamChunk(type="error", error=str(e))
    
    def new_chat(self) -> str:
        """
        Create a new chat session.
        
        Returns:
            New thread_id
            
        Raises:
            requests.exceptions.RequestException: On connection errors
        """
        response = requests.post(f"{self.base_url}/new", headers=self._headers())
        response.raise_for_status()
        return response.json()["thread_id"]
    

    
    # =========================================================================
    # RAW SUPERVISOR METHODS (No CompactingSupervisor wrapper)
    # =========================================================================
    
    def chat_raw(self, message: str, thread_id: Optional[str] = None, timeout: int = 120) -> ChatResponse:
        """
        Send a message to the raw supervisor agent (without context compaction).
        
        This bypasses the CompactingSupervisor wrapper, giving direct access
        to the underlying supervisor agent. Useful for debugging or when you
        want full control over context management.
        
        Args:
            message: The message to send
            thread_id: Optional thread ID for conversation continuity
            timeout: Request timeout in seconds
            
        Returns:
            ChatResponse with content, thread_id, and token_count
            
        Raises:
            requests.exceptions.RequestException: On connection errors
            ValueError: On API errors
        """
        payload = {"message": message, "thread_id": thread_id}
        
        response = requests.post(
            f"{self.base_url}/raw/chat",
            json=payload,
            headers=self._headers(),
            timeout=timeout
        )
        
        if response.status_code != 200:
            error = response.json().get("detail", "Unknown error")
            raise ValueError(f"API error: {error}")
        
        data = response.json()
        return ChatResponse(
            content=data["response"],
            thread_id=data["thread_id"],
            token_count=data["token_count"]
        )
    
    def stream_raw(
        self, 
        message: str, 
        thread_id: Optional[str] = None, 
        timeout: int = 300
    ) -> Generator[StreamChunk, None, None]:
        """
        Stream a response from the raw supervisor agent (without context compaction).
        
        ⚠️ WARNING: This method has known issues and needs to be fixed.
        Use chat_raw() for reliable batch requests.
        
        This bypasses the CompactingSupervisor wrapper, giving direct access
        to the underlying supervisor agent's streaming capabilities.
        
        Args:
            message: The message to send
            thread_id: Optional thread ID for conversation continuity
            timeout: Request timeout in seconds
            
        Yields:
            StreamChunk objects with type 'token', 'done', or 'error'
            
        Example:
            full_response = ""
            for chunk in client.stream_raw("Hello"):
                if chunk.type == "token":
                    full_response += chunk.content
                    print(chunk.content, end="", flush=True)
                elif chunk.type == "done":
                    print(f"\\nThread: {chunk.thread_id}")
                elif chunk.type == "error":
                    print(f"Error: {chunk.error}")
        """
        payload = {"message": message, "thread_id": thread_id}
        
        try:
            with requests.post(
                f"{self.base_url}/raw/chat/stream",
                json=payload,
                headers=self._headers(),
                stream=True,
                timeout=timeout
            ) as response:
                if response.status_code != 200:
                    yield StreamChunk(
                        type="error",
                        error=f"API returned status {response.status_code}"
                    )
                    return
                
                current_event = None
                for line in response.iter_lines(decode_unicode=True):
                    if not line:
                        continue
                    
                    if line.startswith("event:"):
                        current_event = line[6:].strip()
                    elif line.startswith("data:") and current_event:
                        try:
                            data = json.loads(line[5:].strip())
                            
                            if current_event == "token":
                                yield StreamChunk(
                                    type="token",
                                    content=data.get("content", "")
                                )
                            elif current_event == "done":
                                yield StreamChunk(
                                    type="done",
                                    thread_id=data.get("thread_id"),
                                    token_count=data.get("token_count", 0)
                                )
                            elif current_event == "error":
                                yield StreamChunk(
                                    type="error",
                                    error=data.get("error", "Unknown error")
                                )
                        except json.JSONDecodeError:
                            continue
                        current_event = None
                        
        except requests.exceptions.ConnectionError:
            yield StreamChunk(
                type="error",
                error="Cannot connect to API. Make sure the server is running."
            )
        except requests.exceptions.Timeout:
            yield StreamChunk(type="error", error="Request timed out.")
        except Exception as e:
            yield StreamChunk(type="error", error=str(e))


    def health(self) -> bool:
        """
        Check if the API is healthy.
        
        Returns:
            True if healthy, False otherwise
        """
        try:
            response = requests.get(f"{self.base_url}/health", timeout=5, headers=self._headers())
            return response.status_code == 200
        except requests.exceptions.RequestException:
            return False