"""
DC Overview Templates - Generate docker-compose and configuration files
"""

from pathlib import Path
from typing import Optional
import os

from jinja2 import Template

from .config import Config, PrometheusConfig


DOCKER_COMPOSE_TEMPLATE = """# DC Overview - GPU Datacenter Monitoring Suite
# Generated by: dc-overview generate-compose
# Documentation: https://github.com/cryptolabsza/dc-overview

services:
  prometheus:
    image: prom/prometheus:latest
    container_name: prometheus
    restart: unless-stopped
    ports:
      - "127.0.0.1:{{ prometheus_port }}:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
      - prometheus-data:/prometheus
    command:
      - "--config.file=/etc/prometheus/prometheus.yml"
      - "--storage.tsdb.retention.time=30d"
      - "--web.enable-lifecycle"

  grafana:
    image: grafana/grafana:latest
    container_name: grafana
    restart: unless-stopped
    ports:
      - "{{ grafana_port }}:3000"
    volumes:
      - grafana-data:/var/lib/grafana
      - ./grafana/dashboards:/etc/grafana/provisioning/dashboards:ro
      - ./grafana/datasources:/etc/grafana/provisioning/datasources:ro
    environment:
      - GF_SECURITY_ADMIN_PASSWORD={{ grafana_password | default('admin', true) }}
      - GF_INSTALL_PLUGINS=grafana-clock-panel,grafana-piechart-panel
      - GF_USERS_ALLOW_SIGN_UP=false

  node-exporter:
    image: prom/node-exporter:latest
    container_name: node-exporter
    restart: unless-stopped
    network_mode: host
    pid: host
    volumes:
      - "/:/host:ro,rslave"
    command:
      - "--path.rootfs=/host"
{% if vast_api_key %}

  vastai-exporter:
    image: ghcr.io/cryptolabsza/vastai-exporter:latest
    container_name: vastai-exporter
    restart: unless-stopped
    ports:
      - "8622:8622"
    command:
      - "-api-key"
      - "{{ vast_api_key }}"
{% endif %}

volumes:
  prometheus-data:
  grafana-data:
"""

GRAFANA_DATASOURCE_TEMPLATE = """apiVersion: 1

datasources:
  - name: Prometheus
    type: prometheus
    access: proxy
    url: http://prometheus:9090
    isDefault: true
    editable: true
    uid: prometheus
"""

GRAFANA_DASHBOARD_PROVISIONING = """apiVersion: 1

providers:
  - name: 'default'
    orgId: 1
    folder: ''
    type: file
    disableDeletion: false
    updateIntervalSeconds: 10
    allowUiUpdates: true
    options:
      path: /etc/grafana/provisioning/dashboards
"""


def generate_docker_compose(config_dir: Path) -> str:
    """Generate docker-compose.yml content."""
    config = Config.load(config_dir)
    
    template = Template(DOCKER_COMPOSE_TEMPLATE)
    
    return template.render(
        prometheus_port=config.prometheus_port,
        grafana_port=config.grafana_port,
        grafana_password=config.get("master", {}).get("grafana_password"),
        vast_api_key=config.get("vast_api_key"),
    )


def generate_prometheus_yml(config_dir: Path) -> str:
    """Generate prometheus.yml content."""
    prom_config = PrometheusConfig.load(config_dir)
    return prom_config.get_prometheus_yml()


def setup_grafana_provisioning(config_dir: Path):
    """Set up Grafana provisioning directories and files."""
    grafana_dir = config_dir / "grafana"
    
    # Create directories
    (grafana_dir / "dashboards").mkdir(parents=True, exist_ok=True)
    (grafana_dir / "datasources").mkdir(parents=True, exist_ok=True)
    
    # Write datasource config
    with open(grafana_dir / "datasources" / "prometheus.yml", "w") as f:
        f.write(GRAFANA_DATASOURCE_TEMPLATE)
    
    # Write dashboard provisioning
    with open(grafana_dir / "dashboards" / "dashboards.yml", "w") as f:
        f.write(GRAFANA_DASHBOARD_PROVISIONING)
    
    # Copy default dashboards if available
    # These would be bundled with the package
    _copy_bundled_dashboards(grafana_dir / "dashboards")


def _copy_bundled_dashboards(target_dir: Path):
    """Copy bundled Grafana dashboards to target directory."""
    import importlib.resources
    
    try:
        # Try to load bundled dashboards
        dashboards = [
            "dc-overview.json",
            "node-exporter-full.json",
            "nvidia-dcgm.json",
        ]
        
        for dashboard in dashboards:
            # Check if file exists in package
            try:
                with importlib.resources.files("dc_overview.templates").joinpath(dashboard).open() as src:
                    with open(target_dir / dashboard, "w") as dst:
                        dst.write(src.read())
            except Exception:
                pass  # Dashboard not bundled
                
    except Exception:
        pass  # No bundled dashboards


def generate_env_file(config_dir: Path) -> str:
    """Generate .env file content."""
    config = Config.load(config_dir)
    
    lines = [
        "# DC Overview Environment Configuration",
        "# Generated by: dc-overview generate-compose",
        "",
        "# Grafana",
        f"GRAFANA_ADMIN_PASS={config.get('master', {}).get('grafana_password', 'admin')}",
        "",
    ]
    
    if config.get("vast_api_key"):
        lines.extend([
            "# Vast.ai",
            f"VAST_API_KEY={config.get('vast_api_key')}",
            "",
        ])
    
    lines.extend([
        "# Note: This file contains secrets - do not commit to git!",
    ])
    
    return "\n".join(lines)
