"""
Placeholder Registry Export Integration

Integrates the new placeholder registry with the existing export system.
Provides backward-compatible export with enhanced metadata from registry.
"""

from typing import Dict, List
from placeholder_registry import get_registry, EvidenceType


def get_registry_metadata_for_export(profile_id: str) -> Dict:
    """
    Get metadata from registry formatted for export.

    Returns:
        Dict with:
        - flat: List of all metadata dicts
        - by_category: Dict mapping category to list of metadata
        - evidence_report: Statistics about evidence types
        - validation_report: Validation issues
    """
    registry = get_registry()

    # Get all metadata
    all_metadata = registry.get_all()

    # Build flat export
    flat = []
    for key, metadata in sorted(all_metadata.items()):
        meta_dict = metadata.to_dict()
        flat.append(meta_dict)

    # Build by_category
    by_category = {}
    for metadata in all_metadata.values():
        cat = metadata.category
        if cat not in by_category:
            by_category[cat] = []
        by_category[cat].append(metadata.to_dict())

    # Evidence report
    evidence_stats = {
        "code_derived": len(registry.get_by_evidence_type(EvidenceType.CODE_DERIVED)),
        "draft_derived": len(registry.get_by_evidence_type(EvidenceType.DRAFT_DERIVED)),
        "mixed": len(registry.get_by_evidence_type(EvidenceType.MIXED)),
        "unresolved": len(registry.get_by_evidence_type(EvidenceType.UNRESOLVED)),
        "to_verify": len(registry.get_by_evidence_type(EvidenceType.TO_VERIFY))
    }

    evidence_detail = {
        etype.value: registry.get_by_evidence_type(etype)
        for etype in EvidenceType
    }

    # Validation report
    validation_issues = registry.validate_all()

    return {
        "flat": flat,
        "by_category": by_category,
        "evidence_report": {
            "statistics": evidence_stats,
            "detail": evidence_detail
        },
        "validation_report": validation_issues
    }


def merge_registry_with_legacy_export(
    registry_data: Dict,
    legacy_data: Dict,
    resolved_values: Dict[str, str]
) -> Dict:
    """
    Merge registry metadata with legacy export data.

    Args:
        registry_data: Data from get_registry_metadata_for_export()
        legacy_data: Existing legacy export structure
        resolved_values: Resolved placeholder values (key -> value)

    Returns:
        Merged export with registry enhancements
    """
    # Start with legacy structure
    merged = legacy_data.copy()

    # Add registry metadata section
    merged["registry_metadata"] = {
        "flat": registry_data["flat"],
        "by_category": registry_data["by_category"],
        "evidence_report": registry_data["evidence_report"],
        "validation_report": registry_data["validation_report"]
    }

    # Populate runtime values in registry metadata
    for meta_dict in merged["registry_metadata"]["flat"]:
        key = meta_dict["key"]
        if key in resolved_values:
            meta_dict["value_display"] = resolved_values[key]
            # Note: value_raw extraction can be added here if needed

    return merged


def get_enhanced_export_with_registry(profile_id: str, legacy_export: Dict) -> Dict:
    """
    Enhance legacy export with registry metadata.

    Args:
        profile_id: User profile ID
        legacy_export: Existing legacy export structure

    Returns:
        Enhanced export with registry metadata section
    """
    # Get registry data
    registry_data = get_registry_metadata_for_export(profile_id)

    # Get resolved values (for value_display population)
    from placeholder_resolver import get_placeholder_example_values
    resolved_values = get_placeholder_example_values(profile_id)
    cleaned_values = {
        key.replace('{{', '').replace('}}', ''): value
        for key, value in resolved_values.items()
    }

    # Merge
    enhanced = merge_registry_with_legacy_export(
        registry_data,
        legacy_export,
        cleaned_values
    )

    return enhanced
