import json

from fastapi import APIRouter, Depends
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_db, get_current_user
from app.models.user import User
from app.models.industry_config import IndustryConfig

router = APIRouter(tags=["industries"])


@router.get("/industries")
async def list_active_industries(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """Public endpoint: list all active industries."""
    result = await db.execute(
        select(IndustryConfig)
        .where(IndustryConfig.is_active == True)
        .order_by(IndustryConfig.sort_order)
    )
    industries = result.scalars().all()
    items = []
    for ind in industries:
        skills = []
        if ind.skills:
            try:
                raw = json.loads(ind.skills)
                if isinstance(raw, list):
                    if raw and isinstance(raw[0], dict):
                        skills = [s for s in raw if s.get("type") != "skill"]
                    else:
                        skills = [{"key": s, "label": s} for s in raw]
            except (json.JSONDecodeError, TypeError):
                skills = []
        items.append({
            "id": ind.id,
            "key": ind.key,
            "label": ind.label,
            "icon": ind.icon or "",
            "description": ind.description,
            "skills": skills,
            "is_active": ind.is_active,
            "sort_order": ind.sort_order,
        })
    return items
