"""
Admin Training Types Management - v9d Phase 1b

CRUD operations for training types with abilities mapping preparation.
"""
import logging
from typing import Optional
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from psycopg2.extras import Json

from db import get_db, get_cursor, r2d
from auth import require_auth, require_admin
from profile_templates import list_templates, get_template

router = APIRouter(prefix="/api/admin/training-types", tags=["admin", "training-types"])
logger = logging.getLogger(__name__)


class TrainingTypeCreate(BaseModel):
    category: str
    subcategory: Optional[str] = None
    name_de: str
    name_en: str
    icon: Optional[str] = None
    description_de: Optional[str] = None
    description_en: Optional[str] = None
    sort_order: int = 0
    abilities: Optional[dict] = None
    profile: Optional[dict] = None  # Training Type Profile (Phase 2 #15)


class TrainingTypeUpdate(BaseModel):
    category: Optional[str] = None
    subcategory: Optional[str] = None
    name_de: Optional[str] = None
    name_en: Optional[str] = None
    icon: Optional[str] = None
    description_de: Optional[str] = None
    description_en: Optional[str] = None
    sort_order: Optional[int] = None
    abilities: Optional[dict] = None
    profile: Optional[dict] = None  # Training Type Profile (Phase 2 #15)


@router.get("")
def list_training_types_admin(session: dict = Depends(require_admin)):
    """
    Get all training types for admin management.
    Returns full details including abilities.
    """
    with get_db() as conn:
        cur = get_cursor(conn)
        cur.execute("""
            SELECT id, category, subcategory, name_de, name_en, icon,
                   description_de, description_en, sort_order, abilities,
                   profile, created_at
            FROM training_types
            ORDER BY sort_order, category, subcategory
        """)
        rows = cur.fetchall()

    return [r2d(r) for r in rows]


@router.get("/{type_id}")
def get_training_type(type_id: int, session: dict = Depends(require_admin)):
    """Get single training type by ID."""
    with get_db() as conn:
        cur = get_cursor(conn)
        cur.execute("""
            SELECT id, category, subcategory, name_de, name_en, icon,
                   description_de, description_en, sort_order, abilities,
                   profile, created_at
            FROM training_types
            WHERE id = %s
        """, (type_id,))
        row = cur.fetchone()

    if not row:
        raise HTTPException(404, "Training type not found")

    return r2d(row)


@router.post("")
def create_training_type(data: TrainingTypeCreate, session: dict = Depends(require_admin)):
    """Create new training type."""
    with get_db() as conn:
        cur = get_cursor(conn)

        # Convert abilities and profile dict to JSONB
        abilities_json = data.abilities if data.abilities else {}
        profile_json = data.profile if data.profile else None

        cur.execute("""
            INSERT INTO training_types
              (category, subcategory, name_de, name_en, icon,
               description_de, description_en, sort_order, abilities, profile)
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            RETURNING id
        """, (
            data.category,
            data.subcategory,
            data.name_de,
            data.name_en,
            data.icon,
            data.description_de,
            data.description_en,
            data.sort_order,
            Json(abilities_json),
            Json(profile_json) if profile_json else None
        ))

        new_id = cur.fetchone()['id']

        logger.info(f"[ADMIN] Training type created: {new_id} - {data.name_de} ({data.category}/{data.subcategory})")

    return {"id": new_id, "message": "Training type created"}


@router.put("/{type_id}")
def update_training_type(
    type_id: int,
    data: TrainingTypeUpdate,
    session: dict = Depends(require_admin)
):
    """Update existing training type."""
    with get_db() as conn:
        cur = get_cursor(conn)

        # Build update query dynamically
        updates = []
        values = []

        if data.category is not None:
            updates.append("category = %s")
            values.append(data.category)
        if data.subcategory is not None:
            updates.append("subcategory = %s")
            values.append(data.subcategory)
        if data.name_de is not None:
            updates.append("name_de = %s")
            values.append(data.name_de)
        if data.name_en is not None:
            updates.append("name_en = %s")
            values.append(data.name_en)
        if data.icon is not None:
            updates.append("icon = %s")
            values.append(data.icon)
        if data.description_de is not None:
            updates.append("description_de = %s")
            values.append(data.description_de)
        if data.description_en is not None:
            updates.append("description_en = %s")
            values.append(data.description_en)
        if data.sort_order is not None:
            updates.append("sort_order = %s")
            values.append(data.sort_order)
        if data.abilities is not None:
            updates.append("abilities = %s")
            values.append(Json(data.abilities))
        if data.profile is not None:
            updates.append("profile = %s")
            values.append(Json(data.profile))

        if not updates:
            raise HTTPException(400, "No fields to update")

        values.append(type_id)

        cur.execute(f"""
            UPDATE training_types
            SET {', '.join(updates)}
            WHERE id = %s
        """, values)

        if cur.rowcount == 0:
            raise HTTPException(404, "Training type not found")

        logger.info(f"[ADMIN] Training type updated: {type_id}")

    return {"id": type_id, "message": "Training type updated"}


@router.delete("/{type_id}")
def delete_training_type(type_id: int, session: dict = Depends(require_admin)):
    """
    Delete training type.

    WARNING: This will fail if any activities reference this type.
    Consider adding a soft-delete or archive mechanism if needed.
    """
    with get_db() as conn:
        cur = get_cursor(conn)

        # Check if any activities use this type
        cur.execute("""
            SELECT COUNT(*) as count
            FROM activity_log
            WHERE training_type_id = %s
        """, (type_id,))

        count = cur.fetchone()['count']
        if count > 0:
            raise HTTPException(
                400,
                f"Cannot delete: {count} activities are using this training type. "
                "Please reassign or delete those activities first."
            )

        cur.execute("DELETE FROM training_types WHERE id = %s", (type_id,))

        if cur.rowcount == 0:
            raise HTTPException(404, "Training type not found")

        logger.info(f"[ADMIN] Training type deleted: {type_id}")

    return {"message": "Training type deleted"}


@router.get("/taxonomy/abilities")
def get_abilities_taxonomy(session: dict = Depends(require_auth)):
    """
    Get abilities taxonomy for UI and AI analysis.

    This defines the 5 dimensions of athletic development.
    """
    taxonomy = {
        "koordinativ": {
            "name_de": "Koordinative Fähigkeiten",
            "name_en": "Coordination Abilities",
            "icon": "🎯",
            "abilities": [
                {"key": "orientierung", "name_de": "Orientierung", "name_en": "Orientation"},
                {"key": "differenzierung", "name_de": "Differenzierung", "name_en": "Differentiation"},
                {"key": "kopplung", "name_de": "Kopplung", "name_en": "Coupling"},
                {"key": "gleichgewicht", "name_de": "Gleichgewicht", "name_en": "Balance"},
                {"key": "rhythmus", "name_de": "Rhythmisierung", "name_en": "Rhythm"},
                {"key": "reaktion", "name_de": "Reaktion", "name_en": "Reaction"},
                {"key": "umstellung", "name_de": "Umstellung", "name_en": "Adaptation"}
            ]
        },
        "konditionell": {
            "name_de": "Konditionelle Fähigkeiten",
            "name_en": "Conditional Abilities",
            "icon": "💪",
            "abilities": [
                {"key": "kraft", "name_de": "Kraft", "name_en": "Strength"},
                {"key": "ausdauer", "name_de": "Ausdauer", "name_en": "Endurance"},
                {"key": "schnelligkeit", "name_de": "Schnelligkeit", "name_en": "Speed"},
                {"key": "flexibilitaet", "name_de": "Flexibilität", "name_en": "Flexibility"}
            ]
        },
        "kognitiv": {
            "name_de": "Kognitive Fähigkeiten",
            "name_en": "Cognitive Abilities",
            "icon": "🧠",
            "abilities": [
                {"key": "konzentration", "name_de": "Konzentration", "name_en": "Concentration"},
                {"key": "aufmerksamkeit", "name_de": "Aufmerksamkeit", "name_en": "Attention"},
                {"key": "wahrnehmung", "name_de": "Wahrnehmung", "name_en": "Perception"},
                {"key": "entscheidung", "name_de": "Entscheidungsfindung", "name_en": "Decision Making"}
            ]
        },
        "psychisch": {
            "name_de": "Psychische Fähigkeiten",
            "name_en": "Psychological Abilities",
            "icon": "🎭",
            "abilities": [
                {"key": "motivation", "name_de": "Motivation", "name_en": "Motivation"},
                {"key": "willenskraft", "name_de": "Willenskraft", "name_en": "Willpower"},
                {"key": "stressresistenz", "name_de": "Stressresistenz", "name_en": "Stress Resistance"},
                {"key": "selbstvertrauen", "name_de": "Selbstvertrauen", "name_en": "Self-Confidence"}
            ]
        },
        "taktisch": {
            "name_de": "Taktische Fähigkeiten",
            "name_en": "Tactical Abilities",
            "icon": "♟️",
            "abilities": [
                {"key": "timing", "name_de": "Timing", "name_en": "Timing"},
                {"key": "strategie", "name_de": "Strategie", "name_en": "Strategy"},
                {"key": "antizipation", "name_de": "Antizipation", "name_en": "Anticipation"},
                {"key": "situationsanalyse", "name_de": "Situationsanalyse", "name_en": "Situation Analysis"}
            ]
        }
    }

    return taxonomy


# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TRAINING TYPE PROFILES - Phase 2 (#15)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

@router.get("/profiles/templates")
def list_profile_templates(session: dict = Depends(require_admin)):
    """
    List all available profile templates.

    Returns templates for common training types (Running, Meditation, Strength, etc.)
    """
    return list_templates()


@router.get("/profiles/templates/{template_key}")
def get_profile_template(template_key: str, session: dict = Depends(require_admin)):
    """
    Get a specific profile template by key.

    Keys: running, meditation, strength
    """
    template = get_template(template_key)
    if not template:
        raise HTTPException(404, f"Template '{template_key}' not found")
    return template


@router.post("/{type_id}/profile/apply-template")
def apply_profile_template(
    type_id: int,
    data: dict,
    session: dict = Depends(require_admin)
):
    """
    Apply a profile template to a training type.

    Body: { "template_key": "running" }
    """
    template_key = data.get("template_key")
    if not template_key:
        raise HTTPException(400, "template_key required")

    template = get_template(template_key)
    if not template:
        raise HTTPException(404, f"Template '{template_key}' not found")

    # Apply template to training type
    with get_db() as conn:
        cur = get_cursor(conn)

        # Check if training type exists
        cur.execute("SELECT id, name_de FROM training_types WHERE id = %s", (type_id,))
        training_type = cur.fetchone()
        if not training_type:
            raise HTTPException(404, "Training type not found")

        # Update profile
        cur.execute("""
            UPDATE training_types
            SET profile = %s
            WHERE id = %s
        """, (Json(template), type_id))

        logger.info(f"[ADMIN] Applied template '{template_key}' to training type {type_id} ({training_type['name_de']})")

    return {
        "message": f"Template '{template_key}' applied successfully",
        "training_type_id": type_id,
        "training_type_name": training_type['name_de'],
        "template_key": template_key
    }


@router.get("/profiles/stats")
def get_profile_stats(session: dict = Depends(require_admin)):
    """
    Get statistics about configured profiles.

    Returns count of training types with/without profiles.
    """
    with get_db() as conn:
        cur = get_cursor(conn)

        cur.execute("""
            SELECT
                COUNT(*) as total,
                COUNT(profile) as configured,
                COUNT(*) - COUNT(profile) as unconfigured
            FROM training_types
        """)
        stats = cur.fetchone()

        # Get list of types with profiles
        cur.execute("""
            SELECT id, name_de, category, subcategory
            FROM training_types
            WHERE profile IS NOT NULL
            ORDER BY name_de
        """)
        configured_types = [r2d(r) for r in cur.fetchall()]

        # Get list of types without profiles
        cur.execute("""
            SELECT id, name_de, category, subcategory
            FROM training_types
            WHERE profile IS NULL
            ORDER BY name_de
        """)
        unconfigured_types = [r2d(r) for r in cur.fetchall()]

    return {
        "total": stats['total'],
        "configured": stats['configured'],
        "unconfigured": stats['unconfigured'],
        "configured_types": configured_types,
        "unconfigured_types": unconfigured_types
    }
