#!/usr/bin/env python3
"""Cariflex - Crée les assets et sensors pour la simulation météo et prix DSO."""

import json
import requests
import re
import warnings
warnings.filterwarnings("ignore")
from datetime import datetime, timezone, timedelta

FM_HOST = "https://cariflex.digitribe.fr"
CREDS_FILE = "/tmp/fm_creds.json"

with open(CREDS_FILE) as f:
    creds = json.load(f)

session = requests.Session()
session.verify = False

# Login
r = session.get(f"{FM_HOST}/login")
match = re.search(r'<input[^>]*csrf_token[^>]*value="([^"]+)"', r.text)
csrf = match.group(1)
r = session.post(f"{FM_HOST}/login", data={
    "email": creds["email"], "password": creds["password"],
    "csrf_token": csrf, "remember": "y"
}, allow_redirects=True)
print(f"Login: {'OK' if 'dashboard' in r.url else 'FAILED'}")

# Get auth token for API
token = r.cookies.get("session", "")
headers = {"Authorization": f"Bearer {token}"} if token else {}

def fm_post(path, data=None, json_data=None):
    url = f"{FM_HOST}/api/v3_0{path}"
    r = session.post(url, data=data, json=json_data)
    return r

def fm_get(path):
    url = f"{FM_HOST}/api/v3_0{path}"
    r = session.get(url)
    return r

# ========================================
# 1. Créer les assets météo
# ========================================
print("\n=== Création des assets météo ===")

meteo_assets = [
    {
        "name": "Météo Martinique",
        "asset_type_name": "Weather Station",
        "latitude": 14.6091,
        "longitude": -61.2155,
        "sensors": [
            {"name": "irradiance", "unit": "W/m²"},
            {"name": "temperature", "unit": "°C"},
            {"name": "wind_speed", "unit": "m/s"},
            {"name": "humidity", "unit": "%"},
        ]
    },
    {
        "name": "Prix DSO",
        "asset_type_name": "Market",
        "latitude": 14.6091,
        "longitude": -61.2155,
        "sensors": [
            {"name": "consumption_price", "unit": "EUR/MWh"},
            {"name": "production_price", "unit": "EUR/MWh"},
        ]
    }
]

for asset in meteo_assets:
    r = fm_post("/assets", json_data={
        "name": asset["name"],
        "latitude": asset["latitude"],
        "longitude": asset["longitude"],
    })
    print(f"  Asset '{asset['name']}': HTTP {r.status_code}")
    
    if r.status_code in [200, 201]:
        try:
            resp = r.json()
            asset_id = resp.get("id")
            print(f"    ID: {asset_id}")
        except:
            print(f"    Response: {r.text[:200]}")
    else:
        print(f"    Error: {r.text[:200]}")

print("\n=== Simulation setup complete ===")
