#!/usr/bin/env python3
"""Cariflex - Initialise les actifs FlexMeasures dans la base de donnees."""
import subprocess

def run_sql(query):
    result = subprocess.run([
        "docker", "exec", "flexmeasures-db", "psql", "-U", "flexmeasures", "-d", "flexmeasures",
        "-t", "-c", query
    ], capture_output=True, text=True)
    return result.stdout.strip()

# 1. Create asset types
print("=== Creating asset types ===")
asset_types = [
    ("Panneau Photovoltaique", "Installation de production d'energie solaire"),
    ("Batterie de Stockage", "Systeme de stockage d'energie par batterie"),
    ("Borne de Recharge VE", "Station de recharge pour vehicules electriques"),
    ("Vehicule Electrique", "Vehicule electrique avec capacite vehicle-to-grid"),
]
for name, desc in asset_types:
    run_sql("INSERT INTO generic_asset_type (name, description) SELECT '{}', '{}' WHERE NOT EXISTS (SELECT 1 FROM generic_asset_type WHERE name = '{}');".format(name, desc, name))

types = run_sql("SELECT id, name FROM generic_asset_type;")
print(types)

# Get type IDs from DB
type_map = {}
for line in types.split('\n'):
    parts = [p.strip() for p in line.split('|')]
    if len(parts) == 2:
        type_map[parts[1]] = int(parts[0])

pv_type = type_map.get('Panneau Photovoltaique', 1)
bat_type = type_map.get('Batterie de Stockage', 2)
chg_type = type_map.get('Borne de Recharge VE', 3)
ev_type = type_map.get('Vehicule Electrique', 4)

print("Type IDs: PV={}, Bat={}, Charger={}, EV={}".format(pv_type, bat_type, chg_type, ev_type))

# 2. Create 10 assets of each type
print("\n=== Creating assets ===")
base_lat = 14.6091
base_lon = -61.2155

configs = [
    ('PV', pv_type, 'kW', 'capacity', 5),
    ('Bat', bat_type, 'kWh', 'capacity', 100),
    ('Chg', chg_type, 'kW', 'max_power', 22),
    ('EV', ev_type, 'kWh', 'capacity', 75),
]

for prefix, type_id, unit, attr_key, attr_val in configs:
    for i in range(1, 11):
        name = "{}_{:02d}".format(prefix, i)
        lat = base_lat + (i * 0.01)
        lon = base_lon + (i * 0.01)
        sensor = "{}_{:02d}_power".format(prefix.lower(), i)
        
        # Create asset
        run_sql("""INSERT INTO generic_asset (name, latitude, longitude, generic_asset_type_id, account_id, attributes, flex_context, flex_model, sensors_to_show, sensors_to_show_as_kpis)
            SELECT '{}', {}, {}, {}, 1, '{{"{}": {}}}'::jsonb, '{{}}'::jsonb, '{{}}'::jsonb, '[]'::jsonb, '[]'::jsonb
            WHERE NOT EXISTS (SELECT 1 FROM generic_asset WHERE name = '{}');""".format(name, lat, lon, type_id, attr_key, attr_val, name))
        
        # Get asset ID
        aid = run_sql("SELECT id FROM generic_asset WHERE name = '{}';".format(name))
        if aid:
            # Create sensor
            run_sql("""INSERT INTO sensor (name, unit, timezone, event_resolution, knowledge_horizon_fnc, knowledge_horizon_par, generic_asset_id, attributes)
                SELECT '{}', '{}', 'America/Martinique', '00:05:00', 'x_days_ago_at_y_oclock', '{{"x": 1, "y": 13, "z": "America/Martinique"}}'::json, {}, '{{}}'::jsonb
                WHERE NOT EXISTS (SELECT 1 FROM sensor WHERE name = '{}');""".format(sensor, unit, aid, sensor))
            print("  {} (ID:{}) -> sensor {}".format(name, aid, sensor))
        else:
            print("  {} already exists".format(name))

print("\n=== Summary ===")
for prefix, type_id, unit, _, _ in configs:
    n_assets = run_sql("SELECT COUNT(*) FROM generic_asset WHERE generic_asset_type_id = {};".format(type_id))
    n_sensors = run_sql("SELECT COUNT(*) FROM sensor WHERE generic_asset_id IN (SELECT id FROM generic_asset WHERE generic_asset_type_id = {});".format(type_id))
    print("  {}: {} assets, {} sensors".format(prefix, n_assets, n_sensors))
