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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
"""
Audit Logger for Device, Media, and Smart Home Actions

This module provides comprehensive audit logging for all sensitive operations
in Personal Edition. Tracks media control (Spotify, Sonos), smart home
(Hue, Home Assistant), and creative (FFmpeg) actions with structured JSON logs.

Features:
- Structured JSON logging with timestamp, user_id, agent_id, action, service
- Separate audit log file: logs/audit.log (rotates daily)
- Action categories: media, smarthome, creative, local_only_block
- Query methods for retrieving audit logs by user or service
- Log rotation and retention (90 days default, gzip compressed)
- Async logging to avoid blocking operations
- IP address tracking for network security

Log Format:
{
  "timestamp": "2026-02-20T10:30:00Z",
  "user_id": "user_123",
  "agent_id": "agent_456",
  "action": "pause_playback",
  "category": "media",
  "service": "spotify",
  "details": {"device_id": "device_abc"},
  "result": "success",
  "ip_address": "192.168.1.100"
}

Configuration:
- Environment: AUDIT_LOG_PATH (default: logs/audit.log)
- Environment: AUDIT_LOG_RETENTION_DAYS (default: 90)

Usage:
    from core.privsec.audit_logger import AuditLogger

    audit = AuditLogger()
    audit.log_media_action(
        user_id="user_123",
        agent_id="agent_456",
        action="pause_playback",
        service="spotify",
        details={"device_id": "device_abc"},
        result="success"
    )
"""

import asyncio
import gzip
import logging
import os
import json
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, List, Optional

from core.structured_logger import get_logger

logger = get_logger(__name__)


# ============================================================================
# Configuration
# ============================================================================

AUDIT_LOG_PATH = os.getenv("AUDIT_LOG_PATH", "logs/audit.log")
AUDIT_LOG_RETENTION_DAYS = int(os.getenv("AUDIT_LOG_RETENTION_DAYS", "90"))


# ============================================================================
# Audit Logger Service
# ============================================================================

class AuditLogger:
    """
    Singleton service for structured audit logging.

    Provides methods for logging media, smart home, and creative actions.
    Writes to separate audit log file with JSON formatting.
    Implements log rotation and retention policies.

    Thread-safe: Uses module-level singleton instance
    """

    _instance: Optional['AuditLogger'] = None

    def __new__(cls) -> 'AuditLogger':
        """Implement singleton pattern."""
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        """Initialize audit logger (only runs once due to singleton)."""
        if hasattr(self, '_initialized'):
            return

        self._initialized = True
        self._log_path = Path(AUDIT_LOG_PATH)
        self._retention_days = AUDIT_LOG_RETENTION_DAYS

        # Create logs directory if it doesn't exist
        self._log_path.parent.mkdir(parents=True, exist_ok=True)

        # Setup file handler for audit logs
        self._setup_file_handler()

        logger.info(
            "AuditLogger initialized",
            extra={
                "log_path": str(self._log_path),
                "retention_days": self._retention_days
            }
        )

    def _setup_file_handler(self):
        """Setup separate file handler for audit logs."""
        self._audit_handler = logging.FileHandler(self._log_path)
        self._audit_handler.setFormatter(
            logging.Formatter('%(message)s')  # JSON only, no prefix
        )

        # Create audit-specific logger
        self._audit_logger = logging.getLogger('atom.audit')
        self._audit_logger.addHandler(self._audit_handler)
        self._audit_logger.setLevel(logging.INFO)
        self._audit_logger.propagate = False  # Don't propagate to root logger

    def _write_audit_log(
        self,
        user_id: str,
        agent_id: Optional[str],
        action: str,
        category: str,
        service: str,
        details: Dict[str, Any],
        result: str,
        ip_address: Optional[str] = None
    ):
        """
        Write audit log entry (internal method).

        Args:
            user_id: User ID performing action
            agent_id: Agent ID (None if human action)
            action: Action performed (e.g., "pause_playback")
            category: Action category (media, smarthome, creative, local_only_block)
            service: Service name (spotify, sonos, hue, etc.)
            details: Additional details (device_id, track_uri, etc.)
            result: Result (success, failed, blocked, error)
            ip_address: Client IP address (optional)
        """
        log_entry = {
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "user_id": user_id,
            "agent_id": agent_id,
            "action": action,
            "category": category,
            "service": service,
            "details": details,
            "result": result,
            "ip_address": ip_address
        }

        # Write as JSON (single line)
        self._audit_logger.info(json.dumps(log_entry))

    # ========================================================================
    # Media Action Logging
    # ========================================================================

    def log_media_action(
        self,
        user_id: str,
        agent_id: Optional[str],
        action: str,
        service: str,
        details: Dict[str, Any],
        result: str
    ):
        """
        Log media control action (Spotify, Sonos).

        Args:
            user_id: User ID
            agent_id: Agent ID (None if human)
            action: Action (play, pause, skip, volume, etc.)
            service: Service name (spotify, sonos)
            details: Additional details (track_uri, device_id, speaker_ip)
            result: Result (success, failed, blocked)
        """
        self._write_audit_log(
            user_id=user_id,
            agent_id=agent_id,
            action=action,
            category="media",
            service=service,
            details=details,
            result=result
        )

    # ========================================================================
    # Smart Home Action Logging
    # ========================================================================

    def log_smarthome_action(
        self,
        user_id: str,
        agent_id: Optional[str],
        action: str,
        service: str,
        details: Dict[str, Any],
        result: str
    ):
        """
        Log smart home action (Hue, Home Assistant).

        Args:
            user_id: User ID
            agent_id: Agent ID (None if human)
            action: Action (turn_on, turn_off, set_color, etc.)
            service: Service name (hue, home_assistant)
            details: Additional details (light_id, entity_id, bridge_ip)
            result: Result (success, failed, blocked)
        """
        self._write_audit_log(
            user_id=user_id,
            agent_id=agent_id,
            action=action,
            category="smarthome",
            service=service,
            details=details,
            result=result
        )

    # ========================================================================
    # Creative Action Logging
    # ========================================================================

    def log_creative_action(
        self,
        user_id: str,
        agent_id: Optional[str],
        action: str,
        operation: str,
        details: Dict[str, Any],
        result: str
    ):
        """
        Log creative tool action (FFmpeg).

        Args:
            user_id: User ID
            agent_id: Agent ID (None if human)
            action: Action (trim_video, extract_audio, etc.)
            operation: FFmpeg operation
            details: Additional details (input_path, output_path, job_id)
            result: Result (success, failed, blocked)
        """
        self._write_audit_log(
            user_id=user_id,
            agent_id=agent_id,
            action=action,
            category="creative",
            service="ffmpeg",
            details={**details, "operation": operation},
            result=result
        )

    # ========================================================================
    # Local-Only Mode Logging
    # ========================================================================

    def log_local_only_block(
        self,
        user_id: str,
        agent_id: Optional[str],
        service: str,
        attempted_action: str,
        reason: Optional[str] = None
    ):
        """
        Log when local-only mode blocks external service request.

        Args:
            user_id: User ID
            agent_id: Agent ID (None if human)
            service: Service being accessed (spotify, notion, etc.)
            attempted_action: Action being attempted
            reason: Reason for blocking (optional)
        """
        details = {
            "attempted_action": attempted_action
        }
        if reason:
            details["reason"] = reason

        self._write_audit_log(
            user_id=user_id,
            agent_id=agent_id,
            action=f"blocked_{attempted_action}",
            category="local_only_block",
            service=service,
            details=details,
            result="blocked"
        )

    # ========================================================================
    # Query Methods
    # ========================================================================

    def get_user_audit_log(self, user_id: str, limit: int = 100) -> List[Dict]:
        """
        Retrieve audit entries for specific user.

        Args:
            user_id: User ID to query
            limit: Maximum number of entries (default: 100)

        Returns:
            List of audit log entries (most recent first)
        """
        entries = []

        try:
            with open(self._log_path, 'r') as f:
                for line in f:
                    try:
                        entry = json.loads(line.strip())
                        if entry.get('user_id') == user_id:
                            entries.append(entry)
                            if len(entries) >= limit:
                                break
                    except json.JSONDecodeError:
                        continue

        except FileNotFoundError:
            logger.warning(f"Audit log file not found: {self._log_path}")
            return []

        # Return most recent first
        return list(reversed(entries))

    def get_service_audit_log(self, service: str, limit: int = 100) -> List[Dict]:
        """
        Retrieve audit entries for specific service.

        Args:
            service: Service name to query (spotify, sonos, hue, etc.)
            limit: Maximum number of entries (default: 100)

        Returns:
            List of audit log entries (most recent first)
        """
        entries = []

        try:
            with open(self._log_path, 'r') as f:
                for line in f:
                    try:
                        entry = json.loads(line.strip())
                        if entry.get('service') == service:
                            entries.append(entry)
                            if len(entries) >= limit:
                                break
                    except json.JSONDecodeError:
                        continue

        except FileNotFoundError:
            logger.warning(f"Audit log file not found: {self._log_path}")
            return []

        # Return most recent first
        return list(reversed(entries))

    # ========================================================================
    # Log Rotation and Retention
    # ========================================================================

    def rotate_audit_logs(self):
        """
        Rotate audit logs (compress old logs).

        Compresses logs older than today with gzip.
        Should be called daily (e.g., via cron or scheduler).
        """
        today = datetime.utcnow().date()

        # Check if current log file exists
        if not self._log_path.exists():
            return

        # Get current log file modification time
        mtime = datetime.fromtimestamp(self._log_path.stat().st_mtime)

        # If log is from yesterday, rotate it
        if mtime.date() < today:
            yesterday = mtime.date()
            rotated_path = self._log_path.with_suffix(
                f'.{yesterday.strftime("%Y-%m-%d")}.log'
            )

            # Rename with date suffix
            self._log_path.rename(rotated_path)

            # Compress with gzip
            compressed_path = rotated_path.with_suffix('.log.gz')
            with open(rotated_path, 'rb') as f_in:
                with gzip.open(compressed_path, 'wb') as f_out:
                    f_out.writelines(f_in)

            # Remove uncompressed file
            rotated_path.unlink()

            logger.info(
                "Audit log rotated and compressed",
                extra={
                    "rotated_path": str(rotated_path),
                    "compressed_path": str(compressed_path)
                }
            )

            # Re-create file handler for new log
            self._audit_handler.close()
            self._setup_file_handler()

    def cleanup_old_audit_logs(self):
        """
        Remove audit logs older than retention period.

        Should be called daily (e.g., via cron or scheduler).
        """
        cutoff_date = datetime.utcnow() - timedelta(days=self._retention_days)
        removed_count = 0

        # Find all audit log files (including rotated)
        log_pattern = self._log_path.stem + ".*.log*"
        for log_file in self._log_path.parent.glob(log_pattern):
            try:
                # Check file modification time
                mtime = datetime.fromtimestamp(log_file.stat().st_mtime)

                if mtime < cutoff_date:
                    log_file.unlink()
                    removed_count += 1
                    logger.info(
                        "Old audit log removed",
                        extra={
                            "file": str(log_file),
                            "age_days": (datetime.utcnow() - mtime).days
                        }
                    )

            except Exception as e:
                logger.error(
                    "Failed to remove old audit log",
                    extra={
                        "file": str(log_file),
                        "error": str(e)
                    }
                )

        if removed_count > 0:
            logger.info(
                "Audit log cleanup complete",
                extra={"removed_count": removed_count}
            )


# ============================================================================
# Async Logging Helpers
# ============================================================================

async def log_media_action_async(
    user_id: str,
    agent_id: Optional[str],
    action: str,
    service: str,
    details: Dict[str, Any],
    result: str
):
    """
    Async wrapper for media action logging.

    Runs logging in background thread to avoid blocking.
    """
    loop = asyncio.get_event_loop()
    await loop.run_in_executor(
        None,
        lambda: AuditLogger().log_media_action(
            user_id=user_id,
            agent_id=agent_id,
            action=action,
            service=service,
            details=details,
            result=result
        )
    )


async def log_smarthome_action_async(
    user_id: str,
    agent_id: Optional[str],
    action: str,
    service: str,
    details: Dict[str, Any],
    result: str
):
    """
    Async wrapper for smart home action logging.

    Runs logging in background thread to avoid blocking.
    """
    loop = asyncio.get_event_loop()
    await loop.run_in_executor(
        None,
        lambda: AuditLogger().log_smarthome_action(
            user_id=user_id,
            agent_id=agent_id,
            action=action,
            service=service,
            details=details,
            result=result
        )
    )


# ============================================================================
# Module-Level Singleton Instance
# ============================================================================

_audit_logger_instance: Optional[AuditLogger] = None


def get_audit_logger() -> AuditLogger:
    """
    Get singleton AuditLogger instance.

    Returns:
        AuditLogger singleton instance
    """
    global _audit_logger_instance
    if _audit_logger_instance is None:
        _audit_logger_instance = AuditLogger()
    return _audit_logger_instance