#!/usr/bin/env python3
"""
Cariflex - OpenADR VTN (Virtual Top Node) Simulé
Envoie des signaux DSR (prix, charge/décharge) au VEN Cariflex.
"""

import asyncio
import random
from datetime import datetime, timezone, timedelta
from openleadr import OpenADRServer, enable_default_logging
from openleadr.objects import Interval
import logging

enable_default_logging()
logger = logging.getLogger("openleadr")

VTN_ID = "Cariflex-VTN"
VEN_ID = "Cariflex-VEN"
PORT = 8082  # Use 8082 to avoid conflicts


async def ven_lookup(ven_id, *args, **kwargs):
    """Look up a VEN by ID - required for auto-registration."""
    logger.info(f"VEN lookup: {ven_id}")
    if ven_id == VEN_ID:
        return {"ven_name": VEN_ID}
    return None


async def main():
    server = OpenADRServer(
        vtn_id=VTN_ID,
        http_port=PORT,
        http_host="0.0.0.0",
        ven_lookup=ven_lookup,  # This enables auto-registration
    )
    
    logger.info(f"Starting Cariflex VTN: {VTN_ID} on port {PORT}")
    
    # Create price event
    now = datetime.now(timezone.utc)
    price_intervals = []
    for h in range(24):
        dt = now + timedelta(hours=h)
        hour_of_day = dt.hour
        if 6 <= hour_of_day <= 22:
            price = round(random.uniform(80, 150), 2)
        else:
            price = round(random.uniform(40, 80), 2)
        price_intervals.append(
            Interval(dtstart=dt, duration=timedelta(hours=1), signal_payload=price)
        )
    
    server.add_event(
        ven_id=VEN_ID,
        signal_name="ENERGY_PRICE",
        signal_type="price",
        intervals=price_intervals,
        event_id=f"price-{now.strftime('%Y%m%d%H%M%S')}",
        targets=[{"ven_id": VEN_ID}],
        market_context="https://cariflex.digitribe.fr/price",
    )
    logger.info(f"Created price event with {len(price_intervals)} intervals")
    
    # Create load control event
    load_intervals = []
    for h in range(4):
        dt = now + timedelta(hours=h)
        payload = random.choice([0.0, 0.0, 0.0, 0.5, 1.0])
        load_intervals.append(
            Interval(dtstart=dt, duration=timedelta(hours=1), signal_payload=payload)
        )
    
    server.add_event(
        ven_id=VEN_ID,
        signal_name="LOAD_CONTROL",
        signal_type="x-loadControlCapacity",
        intervals=load_intervals,
        event_id=f"load-{now.strftime('%Y%m%d%H%M%S')}",
        targets=[{"ven_id": VEN_ID}],
        market_context="https://cariflex.digitribe.fr/load",
    )
    logger.info(f"Created load control event with {len(load_intervals)} intervals")
    logger.info("Created 2 DSR events, starting server...")
    
    # Start server (blocks forever)
    await server.run()


if __name__ == "__main__":
    asyncio.run(main())
