"""
Helpers for loading persisted sheet profiles.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Optional

from g_gremlin.models import NamedRangeProfile, SheetProfile, TabClassification


def load_profile_if_exists(path: str = ".g_gremlin/profile.json") -> Optional[SheetProfile]:
    """
    Load a SheetProfile from disk if present; otherwise return None.
    """
    profile_path = Path(path)
    if not profile_path.exists():
        return None
    data = json.loads(profile_path.read_text(encoding="utf-8"))
    from g_gremlin.models import ColumnProfile, FormulaCell

    column_profiles = [
        ColumnProfile(
            name=cp.get("name", ""),
            index=int(cp.get("index", 0)),
            inferred_type=cp.get("inferred_type", "mixed"),
            non_null_count=int(cp.get("non_null_count", 0)),
            distinct_count=int(cp.get("distinct_count", 0)),
            sample_values=list(cp.get("sample_values", [])),
            has_formula=bool(cp.get("has_formula", False)),
            role=cp.get("role", "unknown"),
            semantic_type=cp.get("semantic_type"),
            validation=cp.get("validation"),
        )
        for cp in data.get("column_profiles", [])
    ]
    formula_cells = [
        FormulaCell(
            a1=fc.get("a1", ""),
            row_index=int(fc.get("row_index", 0)),
            column_index=int(fc.get("column_index", 0)),
            formula=fc.get("formula", ""),
            value=fc.get("value"),
            is_error=bool(fc.get("is_error", False)),
        )
        for fc in data.get("formula_cells", [])
    ]

    named_ranges = [
        NamedRangeProfile(name=nr.get("name", ""), range_a1=nr.get("range_a1", nr.get("range", "")))
        for nr in data.get("named_ranges", [])
    ]

    classification_data = data.get("classification") or None
    classification = (
        TabClassification(
            type=classification_data.get("type", ""),
            confidence=float(classification_data.get("confidence", 0.0)),
            evidence=list(classification_data.get("evidence", [])),
            suggested_grain=classification_data.get("suggested_grain"),
            suggested_primary_key=classification_data.get("suggested_primary_key"),
        )
        if classification_data
        else None
    )

    return SheetProfile(
        spreadsheet_id=data.get("spreadsheet_id", ""),
        sheet_name=data.get("sheet_name", ""),
        a1_range=data.get("a1_range", ""),
        header=list(data.get("header", [])),
        row_count=int(data.get("row_count", 0)),
        column_profiles=column_profiles,
        formula_cells=formula_cells,
        named_ranges=named_ranges,
        classification=classification,
        detected_sfdc_patterns=data.get("detected_sfdc_patterns"),
        structural_profile=data.get("structural_profile"),
    )
