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

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'}")

# Step 1: Check existing asset types
r = session.get(f"{FM_HOST}/api/v3_0/generic_asset_types")
print(f"Asset types: HTTP {r.status_code}")
types = {}
if r.status_code == 200:
    for t in r.json():
        types[t["name"]] = t["id"]
        print(f"  {t['id']}: {t['name']}")

# Step 2: Check existing assets
r = session.get(f"{FM_HOST}/api/v3_0/assets")
print(f"\nAssets: HTTP {r.status_code}")
assets = {}
if r.status_code == 200:
    for a in r.json()[:10]:
        assets[a["name"]] = a["id"]
        print(f"  {a['id']}: {a['name']} ({a.get('generic_asset_type', {}).get('name', '?')})")

# Step 3: Create assets for weather and pricing
# Use existing asset types or create generic ones
print("\n=== Création des assets ===")

new_assets = [
    {"name": "Météo Martinique", "type_id": 1, "lat": 14.6091, "lon": -61.2155},
    {"name": "Marché Énergie", "type_id": 1, "lat": 14.6091, "lon": -61.2155},
]

for asset in new_assets:
    r = session.post(f"{FM_HOST}/api/v3_0/assets", json={
        "name": asset["name"],
        "generic_asset_type_id": asset["type_id"],
        "latitude": asset["lat"],
        "longitude": asset["lon"],
    })
    print(f"  Asset '{asset['name']}': HTTP {r.status_code}")
    if r.status_code == 201:
        aid = r.json().get("id")
        print(f"    ID: {aid}")
        assets[asset["name"]] = aid
    else:
        try:
            err = r.json()
            print(f"    Error: {err.get('message', r.text[:200])}")
        except:
            print(f"    Error: {r.text[:200]}")

print(f"\n=== Assets existants ===")
for name, aid in assets.items():
    print(f"  {aid}: {name}")
