from __future__ import annotations

from typing import Any

from ..base import BasePostgresClient
from .queries import FETCH_PROJECT_MANAGEMENT_SQL


class ProjectManagementMixin(BasePostgresClient):
    """Project management read helpers."""

    def fetch_project_management_records(self) -> list[dict[str, Any]]:
        """Fetch aggregated project management records from PostgreSQL."""
        if not self.is_enabled():
            return []

        try:
            with self.get_connection() as connection:
                with connection.cursor() as cursor:
                    cursor.execute(FETCH_PROJECT_MANAGEMENT_SQL)
                    rows = cursor.fetchall()
            return [self._normalize_project_management_row(row) for row in rows]
        except Exception:
            return []

    def _normalize_project_management_row(self, row: dict[str, Any]) -> dict[str, Any]:
        """Convert JSON-like values from PostgreSQL into plain Python structures."""
        return {
            "project_code": row["project_code"],
            "project_name": row["project_name"],
            "client_name": row["client_name"],
            "location": row["location"],
            "project_manager": row["project_manager"],
            "status": row["status"],
            "current_phase": row["current_phase"],
            "overall_progress_percent": row["overall_progress_percent"],
            "budget_status": row["budget_status"],
            "summary_cards": self._ensure_list(row.get("summary_cards")),
            "phase_progress": self._ensure_list(row.get("phase_progress")),
            "milestones": self._ensure_list(row.get("milestones")),
            "timeline": self._ensure_list(row.get("timeline")),
            "risks": self._ensure_list(row.get("risks")),
            "upcoming_tasks": self._ensure_list(row.get("upcoming_tasks")),
        }
