"""
Destructive ops manifest helpers for HubSpot packs.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional

from g_gremlin.errors import missing_pyyaml_error


@dataclass
class DestructiveManifest:
    archive_properties: List[Dict[str, str]] = field(default_factory=list)
    delete_pipeline_stages: List[Dict[str, str]] = field(default_factory=list)
    delete_workflows: List[str] = field(default_factory=list)

    def allows_property_archive(self, object_type: str, name: str) -> bool:
        for entry in self.archive_properties:
            if (
                str(entry.get("object_type") or entry.get("objectType") or "") == str(object_type)
                and str(entry.get("name") or "") == str(name)
            ):
                return True
        return False

    def allows_stage_delete(self, object_type: str, pipeline_id: str, stage_id: str) -> bool:
        for entry in self.delete_pipeline_stages:
            if (
                str(entry.get("object_type") or entry.get("objectType") or "") == str(object_type)
                and str(entry.get("pipeline_id") or entry.get("pipelineId") or "") == str(pipeline_id)
                and str(entry.get("stage_id") or entry.get("stageId") or "") == str(stage_id)
            ):
                return True
        return False

    def allows_workflow_delete(self, flow_id: str) -> bool:
        return str(flow_id) in {str(item) for item in self.delete_workflows}


def load_destructive_manifest(pack_dir: Path) -> Optional[DestructiveManifest]:
    path = pack_dir / "destructive.yaml"
    if not path.exists():
        return None
    raw_text = path.read_text(encoding="utf-8")
    try:
        import yaml  # type: ignore
    except Exception as exc:
        raise missing_pyyaml_error() from exc
    payload: Dict[str, Any] = yaml.safe_load(raw_text) or {}
    archive_properties = payload.get("archive_properties") or []
    delete_pipeline_stages = payload.get("delete_pipeline_stages") or []
    delete_workflows = payload.get("delete_workflows") or []
    return DestructiveManifest(
        archive_properties=[dict(item) for item in archive_properties] if isinstance(archive_properties, list) else [],
        delete_pipeline_stages=[
            dict(item) for item in delete_pipeline_stages
        ] if isinstance(delete_pipeline_stages, list) else [],
        delete_workflows=[str(item) for item in delete_workflows] if isinstance(delete_workflows, list) else [],
    )
