#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Utility functions for the FHIR to PAD converter.
"""

from datetime import datetime
from typing import Any, Dict, List, Optional
import xml.etree.ElementTree as ET

def parse_iso_date(s: str) -> Optional[datetime]:
    try:
        return datetime.fromisoformat(s.replace("Z", "+00:00"))
    except (ValueError, TypeError):
        try:
            return datetime.fromisoformat(s)
        except (ValueError, TypeError):
            return None

def format_iso_date(d: datetime) -> str:
    return d.date().isoformat()

def get_ref_id(ref: Optional[str]) -> Optional[str]:
    if not ref or "/" not in ref:
        return None
    return ref.split("/")[-1] or None

def ensure_text(el: Optional[ET.Element], default: str = "") -> str:
    if el is None:
        return default
    return (el.text or "").strip()

def collect_effective_dates(resource: Dict[str, Any]) -> List[datetime]:
    dates: List[datetime] = []
    for key in ["effectiveDateTime", "issued", "authoredOn", "date"]:
        val = resource.get(key)
        if isinstance(val, str):
            d = parse_iso_date(val)
            if d:
                dates.append(d)
    meta = resource.get("meta", {})
    if isinstance(meta, dict) and isinstance(meta.get("lastUpdated"), str):
        d = parse_iso_date(meta["lastUpdated"])
        if d:
            dates.append(d)
    return dates
