from dataclasses import dataclass

import pyogrio

from geo.core.reader import read_dataset


@dataclass
class FieldInfo:
    name: str
    type: str


@dataclass
class DatasetInfo:
    path: str
    driver: str
    crs: str
    geometry_type: str
    feature_count: int
    bounds: tuple[float, float, float, float]
    fields: list[FieldInfo]


def inspect(path: str, layer: str | None = None) -> DatasetInfo:
    """Extract metadata from a dataset without reading features."""
    info = pyogrio.read_info(path, layer=layer)
    
    # Handle CRS
    crs = info["crs"]
    crs_str = "Unknown"
    if crs:
        # Check if it's an EPSG string or similar
        if isinstance(crs, str):
            crs_str = crs
        else:
             # Try to extract something useful if it's a dict/object
            crs_str = str(crs)

    # Fields
    fields = [
        FieldInfo(name=name, type=dtype)
        for name, dtype in zip(info["fields"], info["dtypes"]) # pyogrio gives parallel lists
    ]
    
    # Driver and geometry
    driver = info["driver"]
    geometry_type = info["geometry_type"] # might need mapping if format differs
    feature_count = info["features"]
    bounds = info["total_bounds"]

    return DatasetInfo(
        path=path,
        driver=driver,
        crs=crs_str,
        geometry_type=geometry_type,
        feature_count=feature_count,
        bounds=bounds,
        fields=fields,
    )
