"""
Ontology Parser - Parses ontology YAML/dict into OntologyArtifact.

Handles loading from both dictionaries and files, converting raw
YAML structures into typed dataclass instances.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any

import yaml  # type: ignore[import-untyped]

from pycharter.wiki.ontology.models import (
    FieldOntology,
    Lineage,
    OntologyArtifact,
    Relationship,
    RelationshipType,
)
from pycharter.wiki.shared.errors import OntologyError


def _parse_lineage(data: dict[str, Any] | None) -> Lineage | None:
    """Parse lineage from raw dict."""
    if data is None:
        return None
    return Lineage(
        derived_from=data.get("derived_from"),
        source_system=data.get("source_system"),
    )


def _parse_relationships(data: list[dict[str, Any]]) -> list[Relationship]:
    """Parse relationships from raw list of dicts."""
    if not data:
        return []
    relationships = []
    for item in data:
        target = item.get("target", "")
        rel_type_str = item.get("type", "related_to")
        try:
            rel_type = RelationshipType(rel_type_str)
        except ValueError:
            rel_type = RelationshipType.RELATED_TO
        relationships.append(Relationship(target=target, type=rel_type))
    return relationships


def _parse_field_ontology(data: dict[str, Any]) -> FieldOntology:
    """Parse a single field ontology from raw dict."""
    return FieldOntology(
        concept=data.get("concept", ""),
        broader=data.get("broader"),
        definition=data.get("definition"),
        tags=data.get("tags", []),
        owner=data.get("owner"),
        description=data.get("description"),
        deprecated=bool(data.get("deprecated", False)),
        lineage=_parse_lineage(data.get("lineage")),
        relationships=_parse_relationships(data.get("relationships")),
    )


def parse_ontology(ontology_data: dict[str, Any]) -> OntologyArtifact:
    """
    Parse an ontology dictionary into an OntologyArtifact.

    Expected structure:
    {
        "version": "1.0.0",
        "fields": {
            "customer_id": {
                "concept": "Customer Identity",
                "broader": "Entity",
                ...
            }
        }
    }

    Args:
        ontology_data: Ontology data as dictionary

    Returns:
        OntologyArtifact with parsed fields

    Raises:
        OntologyError: If the data is not a valid dictionary
    """
    if not isinstance(ontology_data, dict):
        raise OntologyError(
            f"Ontology data must be a dictionary, got {type(ontology_data).__name__}"
        )

    version = ontology_data.get("version", "0.0.0")
    raw_fields = ontology_data.get("fields", {})

    if not isinstance(raw_fields, dict):
        raise OntologyError(
            f"Ontology 'fields' must be a dictionary, got {type(raw_fields).__name__}"
        )

    fields = {}
    for field_name, field_data in raw_fields.items():
        if not isinstance(field_data, dict):
            raise OntologyError(
                f"Field '{field_name}' must be a dictionary, "
                f"got {type(field_data).__name__}"
            )
        fields[field_name] = _parse_field_ontology(field_data)

    return OntologyArtifact(version=version, fields=fields)


def parse_ontology_file(file_path: str) -> OntologyArtifact:
    """
    Load and parse an ontology file (YAML or JSON).

    Args:
        file_path: Path to ontology file

    Returns:
        OntologyArtifact with parsed fields

    Raises:
        OntologyError: If the file cannot be read or parsed
    """
    path = Path(file_path)

    if not path.exists():
        raise OntologyError(f"Ontology file not found: {file_path}", path=file_path)

    suffix = path.suffix.lower()

    if suffix in (".jsonld", ".json"):
        try:
            from pycharter.wiki.rdf.jsonld_parser import parse_ontology_jsonld
        except ImportError as exc:
            raise OntologyError(
                "JSON-LD support requires the 'ontology' extra: "
                "pip install pycharter[ontology]",
                path=file_path,
            ) from exc
        import json as _json

        try:
            with open(path, "r", encoding="utf-8") as f:
                data = _json.load(f)
        except _json.JSONDecodeError as e:
            raise OntologyError(f"Invalid JSON: {e}", path=file_path) from e
        return parse_ontology_jsonld(data)

    if suffix not in (".yaml", ".yml"):
        raise OntologyError(
            f"Unsupported file format: {suffix}. Supported: .yaml, .yml, .jsonld, .json",
            path=file_path,
        )

    try:
        with open(path, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f)
    except yaml.YAMLError as e:
        raise OntologyError(f"Invalid YAML: {e}", path=file_path) from e

    if not isinstance(data, dict):
        raise OntologyError(
            f"Ontology file must contain a dictionary, got {type(data).__name__}",
            path=file_path,
        )

    return parse_ontology(data)
