"""Seed data generator for demo mode.

Populates the demo SQLite database with sample entities on first run,
giving new users a realistic out-of-the-box experience without needing
real hardware.
"""

import json
from datetime import datetime, timezone

from wled_controller.storage.database import Database
from wled_controller.utils import get_logger

logger = get_logger(__name__)

# Fixed IDs so cross-references are stable
_DEVICE_IDS = {
    "strip": "device_demo0001",
    "matrix": "device_demo0002",
    "ring": "device_demo0003",
}

_TARGET_IDS = {
    "strip": "pt_demo0001",
    "matrix": "pt_demo0002",
}

_PS_IDS = {
    "main": "ps_demo0001",
    "secondary": "ps_demo0002",
}

_CSS_IDS = {
    "gradient": "css_demo0001",
    "cycle": "css_demo0002",
    "picture": "css_demo0003",
    "audio": "css_demo0004",
}

_AS_IDS = {
    "system": "as_demo0001",
}

_TPL_ID = "tpl_demo0001"

_SCENE_ID = "scene_demo0001"

_NOW = datetime.now(timezone.utc).isoformat()


def _insert_entities(db: Database, table: str, items: dict) -> None:
    """Insert entity dicts into a SQLite table."""
    rows = []
    for entity_id, entity_data in items.items():
        name = entity_data.get("name", "")
        data_json = json.dumps(entity_data, ensure_ascii=False)
        rows.append((entity_id, name, data_json))
    if rows:
        db.bulk_insert(table, rows)
        logger.info(f"Seeded {len(rows)} entities into {table}")


def seed_demo_data(db: Database) -> None:
    """Populate demo database with sample entities.

    Only runs when the database has no entities in any table.
    Must be called BEFORE store constructors run so they load the seeded data.
    """
    # Check if any table already has data
    for table in [
        "devices",
        "output_targets",
        "color_strip_sources",
        "picture_sources",
        "audio_sources",
        "scene_presets",
    ]:
        if db.table_exists_with_data(table):
            logger.info("Demo data already exists — skipping seed")
            return

    logger.info("Seeding demo data for first-run experience")

    _insert_entities(db, "devices", _build_devices())
    _insert_entities(db, "capture_templates", _build_capture_templates())
    _insert_entities(db, "output_targets", _build_output_targets())
    _insert_entities(db, "picture_sources", _build_picture_sources())
    _insert_entities(db, "color_strip_sources", _build_color_strip_sources())
    _insert_entities(db, "audio_sources", _build_audio_sources())
    _insert_entities(db, "scene_presets", _build_scene_presets())

    logger.info("Demo seed data complete")


# ── Devices ────────────────────────────────────────────────────────


def _build_devices() -> dict:
    return {
        _DEVICE_IDS["strip"]: {
            "id": _DEVICE_IDS["strip"],
            "name": "Demo LED Strip",
            "url": "demo://demo-strip",
            "led_count": 60,
            "enabled": True,
            "device_type": "demo",
            "created_at": _NOW,
            "updated_at": _NOW,
        },
        _DEVICE_IDS["matrix"]: {
            "id": _DEVICE_IDS["matrix"],
            "name": "Demo LED Matrix",
            "url": "demo://demo-matrix",
            "led_count": 256,
            "enabled": True,
            "device_type": "demo",
            "created_at": _NOW,
            "updated_at": _NOW,
        },
        _DEVICE_IDS["ring"]: {
            "id": _DEVICE_IDS["ring"],
            "name": "Demo LED Ring",
            "url": "demo://demo-ring",
            "led_count": 24,
            "enabled": True,
            "device_type": "demo",
            "created_at": _NOW,
            "updated_at": _NOW,
        },
    }


# ── Capture Templates ──────────────────────────────────────────────


def _build_capture_templates() -> dict:
    return {
        _TPL_ID: {
            "id": _TPL_ID,
            "name": "Demo Capture",
            "engine_type": "demo",
            "engine_config": {},
            "description": "Default capture template using demo engine",
            "tags": ["demo"],
            "created_at": _NOW,
            "updated_at": _NOW,
        },
    }


# ── Output Targets ─────────────────────────────────────────────────


def _build_output_targets() -> dict:
    return {
        _TARGET_IDS["strip"]: {
            "id": _TARGET_IDS["strip"],
            "name": "Strip — Gradient",
            "target_type": "led",
            "device_id": _DEVICE_IDS["strip"],
            "color_strip_source_id": _CSS_IDS["gradient"],
            "brightness": 1.0,
            "fps": 30,
            "keepalive_interval": 1.0,
            "state_check_interval": 30,
            "min_brightness_threshold": 0,
            "adaptive_fps": False,
            "protocol": "ddp",
            "description": "Demo LED strip with gradient effect",
            "tags": ["demo"],
            "created_at": _NOW,
            "updated_at": _NOW,
        },
        _TARGET_IDS["matrix"]: {
            "id": _TARGET_IDS["matrix"],
            "name": "Matrix — Screen Capture",
            "target_type": "led",
            "device_id": _DEVICE_IDS["matrix"],
            "color_strip_source_id": _CSS_IDS["picture"],
            "brightness": 1.0,
            "fps": 30,
            "keepalive_interval": 1.0,
            "state_check_interval": 30,
            "min_brightness_threshold": 0,
            "adaptive_fps": False,
            "protocol": "ddp",
            "description": "Demo LED matrix with screen capture",
            "tags": ["demo"],
            "created_at": _NOW,
            "updated_at": _NOW,
        },
    }


# ── Picture Sources ────────────────────────────────────────────────


def _build_picture_sources() -> dict:
    return {
        _PS_IDS["main"]: {
            "id": _PS_IDS["main"],
            "name": "Demo Display 1080p",
            "stream_type": "raw",
            "display_index": 0,
            "capture_template_id": _TPL_ID,
            "target_fps": 30,
            "description": "Virtual 1920x1080 display capture",
            "tags": ["demo"],
            "created_at": _NOW,
            "updated_at": _NOW,
            "source_stream_id": None,
            "postprocessing_template_id": None,
            "image_asset_id": None,
            "video_asset_id": None,
            "loop": None,
            "playback_speed": None,
            "start_time": None,
            "end_time": None,
            "resolution_limit": None,
            "clock_id": None,
        },
        _PS_IDS["secondary"]: {
            "id": _PS_IDS["secondary"],
            "name": "Demo Display 4K",
            "stream_type": "raw",
            "display_index": 1,
            "capture_template_id": _TPL_ID,
            "target_fps": 30,
            "description": "Virtual 3840x2160 display capture",
            "tags": ["demo"],
            "created_at": _NOW,
            "updated_at": _NOW,
            "source_stream_id": None,
            "postprocessing_template_id": None,
            "image_asset_id": None,
            "video_asset_id": None,
            "loop": None,
            "playback_speed": None,
            "start_time": None,
            "end_time": None,
            "resolution_limit": None,
            "clock_id": None,
        },
    }


# ── Color Strip Sources ────────────────────────────────────────────


def _build_color_strip_sources() -> dict:
    return {
        _CSS_IDS["gradient"]: {
            "id": _CSS_IDS["gradient"],
            "name": "Rainbow Gradient",
            "source_type": "gradient",
            "description": "Smooth rainbow gradient across all LEDs",
            "clock_id": None,
            "tags": ["demo"],
            "stops": [
                {"position": 0.0, "color": [255, 0, 0]},
                {"position": 0.25, "color": [255, 255, 0]},
                {"position": 0.5, "color": [0, 255, 0]},
                {"position": 0.75, "color": [0, 0, 255]},
                {"position": 1.0, "color": [255, 0, 255]},
            ],
            "animation": {"enabled": True, "type": "gradient_shift", "speed": 0.5},
            "created_at": _NOW,
            "updated_at": _NOW,
        },
        _CSS_IDS["cycle"]: {
            "id": _CSS_IDS["cycle"],
            "name": "Warm Color Cycle",
            "source_type": "color_cycle",
            "description": "Smoothly cycles through warm colors",
            "clock_id": None,
            "tags": ["demo"],
            "colors": [
                [255, 60, 0],
                [255, 140, 0],
                [255, 200, 50],
                [255, 100, 20],
            ],
            "created_at": _NOW,
            "updated_at": _NOW,
        },
        _CSS_IDS["picture"]: {
            "id": _CSS_IDS["picture"],
            "name": "Screen Capture — Main Display",
            "source_type": "picture",
            "description": "Captures colors from the main demo display",
            "clock_id": None,
            "tags": ["demo"],
            "picture_source_id": _PS_IDS["main"],
            "fps": 30,
            "smoothing": 0.3,
            "interpolation_mode": "average",
            "calibration": {
                "mode": "simple",
                "layout": "clockwise",
                "start_position": "bottom_left",
                "leds_top": 28,
                "leds_bottom": 28,
                "leds_left": 16,
                "leds_right": 16,
            },
            "led_count": 0,
            "created_at": _NOW,
            "updated_at": _NOW,
        },
        _CSS_IDS["audio"]: {
            "id": _CSS_IDS["audio"],
            "name": "Audio Spectrum",
            "source_type": "audio",
            "description": "Audio-reactive spectrum visualization",
            "clock_id": None,
            "tags": ["demo"],
            "visualization_mode": "spectrum",
            "audio_source_id": _AS_IDS["system"],
            "sensitivity": 1.0,
            "smoothing": 0.3,
            "palette": "rainbow",
            "color": [0, 255, 0],
            "color_peak": [255, 0, 0],
            "led_count": 0,
            "mirror": False,
            "created_at": _NOW,
            "updated_at": _NOW,
        },
    }


# ── Audio Sources ──────────────────────────────────────────────────


def _build_audio_sources() -> dict:
    return {
        _AS_IDS["system"]: {
            "id": _AS_IDS["system"],
            "name": "Demo System Audio",
            "source_type": "capture",
            "device_index": 1,
            "is_loopback": True,
            "audio_template_id": None,
            "description": "Virtual system audio (loopback)",
            "tags": ["demo"],
            "created_at": _NOW,
            "updated_at": _NOW,
            "audio_source_id": None,
            "audio_processing_template_id": None,
        },
    }


# ── Scene Presets ──────────────────────────────────────────────────


def _build_scene_presets() -> dict:
    return {
        _SCENE_ID: {
            "id": _SCENE_ID,
            "name": "Demo Ambient",
            "description": "Activates gradient on the strip and screen capture on the matrix",
            "tags": ["demo"],
            "order": 0,
            "targets": [
                {
                    "target_id": _TARGET_IDS["strip"],
                    "running": True,
                    "color_strip_source_id": _CSS_IDS["gradient"],
                    "brightness": 1.0,
                    "fps": 30,
                },
                {
                    "target_id": _TARGET_IDS["matrix"],
                    "running": True,
                    "color_strip_source_id": _CSS_IDS["picture"],
                    "brightness": 1.0,
                    "fps": 30,
                },
            ],
            "created_at": _NOW,
            "updated_at": _NOW,
        },
    }
