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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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# -*- coding: utf-8 -*-
"""
Smart Home Control Tool

**✅ REAL IMPLEMENTATION**

Provides Philips Hue and Home Assistant control for AI agents with governance integration.
- Local-only execution (no cloud relay)
- Hue light control: on/off, brightness, color, scenes
- Home Assistant entity control: states, services, automations
- SUPERVISED+ maturity level required
- Full audit trail for all device control actions

Architecture:
- Agent -> SmartHomeTool -> HueService/HomeAssistantService -> Local Devices
- Governance check via GovernanceCache before all operations
- Encrypted credential storage via database models
- Audit trail via HueBridge/HomeAssistantConnection models

Governance:
- STUDENT and INTERN agents BLOCKED from smart home control
- SUPERVISED and AUTONOMOUS agents can control devices
- All actions logged with entity identification for accountability
"""

import asyncio
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy.orm import Session

from core.database import get_db_session
from core.governance_cache import GovernanceCache
from core.models import AgentRegistry, User
from core.smarthome.hue_service import HueService
from core.smarthome.home_assistant_service import HomeAssistantService
from core.feature_flags import FeatureFlags
from core.structured_logger import get_logger

logger = get_logger(__name__)

# Initialize governance cache
_governance_cache = GovernanceCache()


# ============================================================================
# Hue Control Functions
# ============================================================================

async def _check_hue_permission(
    agent_id: Optional[str],
    user_id: str
) -> Tuple[bool, Optional[str]]:
    """
    Check if agent has permission for Hue control.

    Args:
        agent_id: Agent ID (None if human-triggered)
        user_id: User ID

    Returns:
        (allowed, reason) tuple
    """
    if not FeatureFlags.SMART_HOME_CONTROL_ENABLED:
        return False, "Smart home control is disabled via feature flag"

    # If no agent_id, it's a human-triggered action (allow)
    if not agent_id:
        return True, None

    # Check governance cache
    cached = _governance_cache.get(agent_id, "hue_control")
    if cached:
        return cached.get("allowed", False), cached.get("reason")

    # Check agent maturity level from database
    try:
        with get_db_session() as db:
            agent = db.query(AgentRegistry).filter(
                AgentRegistry.id == agent_id
            ).first()

            if not agent:
                return False, f"Agent '{agent_id}' not found"

            # Map maturity to allowed
            maturity = agent.maturity_level
            allowed = maturity in ["SUPERVISED", "AUTONOMOUS"]

            reason = None
            if not allowed:
                reason = f"Hue control requires SUPERVISED+ maturity (agent is {maturity})"

            # Cache decision
            _governance_cache.set(agent_id, "hue_control", {
                "allowed": allowed,
                "reason": reason,
                "maturity": maturity
            })

            return allowed, reason

    except Exception as e:
        logger.error("Failed to check Hue permission", agent_id=agent_id, error=str(e))
        return False, f"Permission check failed: {e}"


async def hue_discover_bridges(
    agent_id: Optional[str] = None,
    user_id: str = None
) -> Dict[str, Any]:
    """
    Discover Philips Hue bridges on local network.

    Args:
        agent_id: Agent ID (if agent-triggered)
        user_id: User ID

    Returns:
        Discovery result with bridge IPs

    Raises:
        PermissionError: If agent lacks SUPERVISED maturity
    """
    user_id = user_id or "default"

    # Check governance
    allowed, reason = await _check_hue_permission(agent_id, user_id)
    if not allowed:
        logger.warning("Hue bridge discovery blocked", agent_id=agent_id, reason=reason)
        raise PermissionError(reason)

    try:
        service = HueService()
        bridge_ips = await service.discover_bridges()

        logger.info("Hue bridge discovery successful", agent_id=agent_id, bridge_count=len(bridge_ips))

        return {
            "success": True,
            "bridges": bridge_ips,
            "count": len(bridge_ips),
            "message": f"Found {len(bridge_ips)} Hue bridge(s)"
        }

    except Exception as e:
        logger.error("Hue bridge discovery failed", error=str(e))
        return {
            "success": False,
            "error": str(e),
            "message": "Failed to discover Hue bridges"
        }


async def hue_get_lights(
    agent_id: Optional[str] = None,
    user_id: str = None,
    bridge_ip: str = None,
    api_key: str = None
) -> Dict[str, Any]:
    """
    Get all lights from Hue bridge.

    Args:
        agent_id: Agent ID (if agent-triggered)
        user_id: User ID
        bridge_ip: Hue bridge IP address
        api_key: Hue API v2 key

    Returns:
        List of lights with id, name, on, brightness, color

    Raises:
        PermissionError: If agent lacks SUPERVISED maturity
        ValueError: If bridge_ip or api_key missing
    """
    user_id = user_id or "default"

    # Check governance
    allowed, reason = await _check_hue_permission(agent_id, user_id)
    if not allowed:
        logger.warning("Hue get_lights blocked", agent_id=agent_id, reason=reason)
        raise PermissionError(reason)

    if not bridge_ip or not api_key:
        raise ValueError("bridge_ip and api_key are required")

    try:
        service = HueService()
        lights = await service.get_all_lights(bridge_ip, api_key)

        logger.info("Hue get_lights successful", agent_id=agent_id, light_count=len(lights))

        return {
            "success": True,
            "lights": lights,
            "count": len(lights),
            "message": f"Retrieved {len(lights)} light(s)"
        }

    except Exception as e:
        logger.error("Hue get_lights failed", error=str(e))
        return {
            "success": False,
            "error": str(e),
            "message": "Failed to get Hue lights"
        }


async def hue_set_light_state(
    agent_id: Optional[str] = None,
    user_id: str = None,
    bridge_ip: str = None,
    api_key: str = None,
    light_id: str = None,
    on: Optional[bool] = None,
    brightness: Optional[float] = None,
    color_xy: Optional[Tuple[float, float]] = None
) -> Dict[str, Any]:
    """
    Set state of a Hue light.

    Args:
        agent_id: Agent ID (if agent-triggered)
        user_id: User ID
        bridge_ip: Hue bridge IP address
        api_key: Hue API v2 key
        light_id: Light ID (e.g., "1", "2", "3")
        on: Turn on/off (None = no change)
        brightness: Brightness 0-100 (None = no change)
        color_xy: Color XY coordinates (None = no change)

    Returns:
        Updated light state

    Raises:
        PermissionError: If agent lacks SUPERVISED maturity
        ValueError: If required parameters missing
    """
    user_id = user_id or "default"

    # Check governance
    allowed, reason = await _check_hue_permission(agent_id, user_id)
    if not allowed:
        logger.warning("Hue set_light_state blocked", agent_id=agent_id, reason=reason)
        raise PermissionError(reason)

    if not bridge_ip or not api_key or not light_id:
        raise ValueError("bridge_ip, api_key, and light_id are required")

    try:
        service = HueService()
        light_state = await service.set_light_state(
            bridge_ip, api_key, light_id, on, brightness, color_xy
        )

        logger.info("Hue set_light_state successful", agent_id=agent_id, light_id=light_id)

        return {
            "success": True,
            "light": light_state,
            "message": f"Light '{light_id}' state updated"
        }

    except Exception as e:
        logger.error("Hue set_light_state failed", error=str(e))
        return {
            "success": False,
            "error": str(e),
            "message": f"Failed to set light '{light_id}' state"
        }


# ============================================================================
# Home Assistant Control Functions
# ============================================================================

async def _check_home_assistant_permission(
    agent_id: Optional[str],
    user_id: str
) -> Tuple[bool, Optional[str]]:
    """
    Check if agent has permission for Home Assistant control.

    Args:
        agent_id: Agent ID (None if human-triggered)
        user_id: User ID

    Returns:
        (allowed, reason) tuple
    """
    if not FeatureFlags.SMART_HOME_CONTROL_ENABLED:
        return False, "Smart home control is disabled via feature flag"

    # If no agent_id, it's a human-triggered action (allow)
    if not agent_id:
        return True, None

    # Check governance cache
    cached = _governance_cache.get(agent_id, "home_assistant_control")
    if cached:
        return cached.get("allowed", False), cached.get("reason")

    # Check agent maturity level from database
    try:
        with get_db_session() as db:
            agent = db.query(AgentRegistry).filter(
                AgentRegistry.id == agent_id
            ).first()

            if not agent:
                return False, f"Agent '{agent_id}' not found"

            # Map maturity to allowed
            maturity = agent.maturity_level
            allowed = maturity in ["SUPERVISED", "AUTONOMOUS"]

            reason = None
            if not allowed:
                reason = f"Home Assistant control requires SUPERVISED+ maturity (agent is {maturity})"

            # Cache decision
            _governance_cache.set(agent_id, "home_assistant_control", {
                "allowed": allowed,
                "reason": reason,
                "maturity": maturity
            })

            return allowed, reason

    except Exception as e:
        logger.error("Failed to check Home Assistant permission", agent_id=agent_id, error=str(e))
        return False, f"Permission check failed: {e}"


async def home_assistant_get_states(
    agent_id: Optional[str] = None,
    user_id: str = None,
    ha_url: str = None,
    ha_token: str = None
) -> Dict[str, Any]:
    """
    Get all entity states from Home Assistant.

    Args:
        agent_id: Agent ID (if agent-triggered)
        user_id: User ID
        ha_url: Home Assistant URL
        ha_token: Long-lived access token

    Returns:
        List of entity states

    Raises:
        PermissionError: If agent lacks SUPERVISED maturity
    """
    user_id = user_id or "default"

    # Check governance
    allowed, reason = await _check_home_assistant_permission(agent_id, user_id)
    if not allowed:
        logger.warning("Home Assistant get_states blocked", agent_id=agent_id, reason=reason)
        raise PermissionError(reason)

    if not ha_url or not ha_token:
        raise ValueError("ha_url and ha_token are required")

    try:
        service = HomeAssistantService(ha_url, ha_token)
        states = await service.get_states()
        await service.close()

        logger.info("Home Assistant get_states successful", agent_id=agent_id, entity_count=len(states))

        return {
            "success": True,
            "states": states,
            "count": len(states),
            "message": f"Retrieved {len(states)} entity states"
        }

    except Exception as e:
        logger.error("Home Assistant get_states failed", error=str(e))
        return {
            "success": False,
            "error": str(e),
            "message": "Failed to get entity states"
        }


async def home_assistant_call_service(
    agent_id: Optional[str] = None,
    user_id: str = None,
    ha_url: str = None,
    ha_token: str = None,
    domain: str = None,
    service: str = None,
    entity_id: Optional[str] = None,
    data: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
    """
    Call a Home Assistant service.

    Args:
        agent_id: Agent ID (if agent-triggered)
        user_id: User ID
        ha_url: Home Assistant URL
        ha_token: Long-lived access token
        domain: Domain (e.g., "light", "switch")
        service: Service name (e.g., "turn_on", "turn_off")
        entity_id: Entity ID (optional)
        data: Service data (optional)

    Returns:
        Service call result

    Raises:
        PermissionError: If agent lacks SUPERVISED maturity
    """
    user_id = user_id or "default"

    # Check governance
    allowed, reason = await _check_home_assistant_permission(agent_id, user_id)
    if not allowed:
        logger.warning("Home Assistant call_service blocked", agent_id=agent_id, reason=reason)
        raise PermissionError(reason)

    if not ha_url or not ha_token or not domain or not service:
        raise ValueError("ha_url, ha_token, domain, and service are required")

    try:
        service = HomeAssistantService(ha_url, ha_token)
        result = await service.call_service(domain, service, entity_id, data)
        await service.close()

        logger.info("Home Assistant call_service successful", agent_id=agent_id, domain=domain, service=service)

        return {
            "success": True,
            "result": result,
            "message": f"Service '{domain}.{service}' called successfully"
        }

    except Exception as e:
        logger.error("Home Assistant call_service failed", error=str(e))
        return {
            "success": False,
            "error": str(e),
            "message": f"Failed to call service '{domain}.{service}'"
        }


async def home_assistant_get_lights(
    agent_id: Optional[str] = None,
    user_id: str = None,
    ha_url: str = None,
    ha_token: str = None
) -> Dict[str, Any]:
    """
    Get all light entities from Home Assistant.

    Args:
        agent_id: Agent ID (if agent-triggered)
        user_id: User ID
        ha_url: Home Assistant URL
        ha_token: Long-lived access token

    Returns:
        List of light entity states
    """
    user_id = user_id or "default"

    # Check governance
    allowed, reason = await _check_home_assistant_permission(agent_id, user_id)
    if not allowed:
        logger.warning("Home Assistant get_lights blocked", agent_id=agent_id, reason=reason)
        raise PermissionError(reason)

    if not ha_url or not ha_token:
        raise ValueError("ha_url and ha_token are required")

    try:
        service = HomeAssistantService(ha_url, ha_token)
        lights = await service.get_lights()
        await service.close()

        logger.info("Home Assistant get_lights successful", agent_id=agent_id, light_count=len(lights))

        return {
            "success": True,
            "lights": lights,
            "count": len(lights),
            "message": f"Retrieved {len(lights)} light(s)"
        }

    except Exception as e:
        logger.error("Home Assistant get_lights failed", error=str(e))
        return {
            "success": False,
            "error": str(e),
            "message": "Failed to get lights"
        }


# ============================================================================
# Tool Registration
# ============================================================================

def register_smarthome_tools():
    """
    Register smart home tools with ToolRegistry.

    This function should be called during application startup to register
    all smart home control functions with the tool registry for agent use.
    """
    from tools.registry import tool_registry

    # Register Hue tools
    tool_registry.register(
        name="hue_discover_bridges",
        function=hue_discover_bridges,
        version="1.0.0",
        description="Discover Philips Hue bridges on local network via mDNS. Requires SUPERVISED+ maturity.",
        category="smarthome",
        complexity=2,
        maturity_required="SUPERVISED",
        tags=["hue", "philips-hue", "discovery", "smarthome", "home"]
    )

    tool_registry.register(
        name="hue_get_lights",
        function=hue_get_lights,
        version="1.0.0",
        description="Get all Philips Hue lights with state (on/off, brightness, color). Requires SUPERVISED+ maturity.",
        category="smarthome",
        complexity=2,
        maturity_required="SUPERVISED",
        tags=["hue", "philips-hue", "lights", "smarthome", "home"]
    )

    tool_registry.register(
        name="hue_set_light_state",
        function=hue_set_light_state,
        version="1.0.0",
        description="Set Philips Hue light state (on/off, brightness 0-100, color XY coordinates). Requires SUPERVISED+ maturity.",
        category="smarthome",
        complexity=2,
        maturity_required="SUPERVISED",
        tags=["hue", "philips-hue", "lights", "control", "smarthome", "home"]
    )

    # Register Home Assistant tools
    tool_registry.register(
        name="home_assistant_get_states",
        function=home_assistant_get_states,
        version="1.0.0",
        description="Get all entity states from Home Assistant. Requires SUPERVISED+ maturity.",
        category="smarthome",
        complexity=2,
        maturity_required="SUPERVISED",
        tags=["home-assistant", "states", "smarthome", "home", "automation"]
    )

    tool_registry.register(
        name="home_assistant_call_service",
        function=home_assistant_call_service,
        version="1.0.0",
        description="Call Home Assistant service (e.g., light.turn_on, switch.turn_off, automation.trigger). Requires SUPERVISED+ maturity.",
        category="smarthome",
        complexity=2,
        maturity_required="SUPERVISED",
        tags=["home-assistant", "services", "control", "smarthome", "home", "automation"]
    )

    tool_registry.register(
        name="home_assistant_get_lights",
        function=home_assistant_get_lights,
        version="1.0.0",
        description="Get all light entities from Home Assistant. Requires SUPERVISED+ maturity.",
        category="smarthome",
        complexity=2,
        maturity_required="SUPERVISED",
        tags=["home-assistant", "lights", "smarthome", "home"]
    )

    logger.info("Smart home tools registered with ToolRegistry")


# Auto-register on import
try:
    register_smarthome_tools()
except Exception as e:
    logger.warning(f"Failed to auto-register smart home tools: {e}")