"""Field-related helpers for EDA agent services."""
from __future__ import annotations

import uuid
from typing import List

from fastapi import HTTPException
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession


class FieldService:
    """Validate and resolve active field IDs against Normbase shared table."""

    async def resolve_active_fields(
        self,
        db: AsyncSession,
        requested_active_fields: List[str],
    ) -> List[str]:
        if requested_active_fields:
            return await self.validate_active_fields(db, requested_active_fields)
        row = (
            await db.execute(
                text(
                    """
                    SELECT id::text
                    FROM fields
                    WHERE name = 'default' AND status = 'active'
                    LIMIT 1;
                    """
                )
            )
        ).scalar_one_or_none()
        if not row:
            raise HTTPException(
                status_code=500,
                detail="Default active field not found; cannot initialize active_fields.",
            )
        return [row]

    async def validate_active_fields(
        self,
        db: AsyncSession,
        active_fields: List[str],
    ) -> List[str]:
        if not active_fields:
            raise HTTPException(
                status_code=422,
                detail="active_fields cannot be empty when provided.",
            )
        normalized: List[str] = []
        for value in active_fields:
            try:
                normalized.append(str(uuid.UUID(str(value))))
            except (ValueError, TypeError):
                raise HTTPException(
                    status_code=422,
                    detail=f"active_fields contains non-UUID value: {value}",
                ) from None

        rows = (
            await db.execute(
                text("SELECT id::text FROM fields WHERE id::text = ANY(:ids) AND status = 'active';"),
                {"ids": normalized},
            )
        ).scalars().all()
        existing = {str(r) for r in rows}
        missing = [field_id for field_id in normalized if field_id not in existing]
        if missing:
            raise HTTPException(
                status_code=422,
                detail=f"active_fields contains non-active or unknown field IDs: {missing}",
            )
        return normalized
