from datetime import datetime


# ===== CSV Metadata Model =====
class CSVFileMetadata:
    # ===== Lifecycle =====
    def __init__(self, wafer="", date="", chamber="", notes="", master_type="", filename="", columns=0):
        self.wafer = wafer
        self.date = date
        self.chamber = chamber
        self.notes = notes
        self.master_type = master_type

        self.filename = filename
        self.columns = columns

    # ===== Accessors =====
    def get_wafer_type(self) -> str:
        """Return the first character of the wafer string, or empty if none"""
        return self.wafer[0] if self.wafer else ""

    def get_date(self) -> datetime | None:
        """Parsifes the date string. Returns None if parsing fails"""
        date_format = "%Y-%m-%d %H:%M:%S"
        try:
            return datetime.strptime(self.date, date_format)
        except (ValueError, TypeError):
            # If format is wrong or date is None, return None
            return None

    # ===== Formatting =====
    @staticmethod
    def format_date(dt: datetime) -> str:
        """Formats a datetime object into the standard ISO-like string."""
        if not isinstance(dt, datetime):
            return ""
        return dt.strftime("%Y-%m-%d %H:%M:%S")

    # ===== Serialization =====
    def to_dict(self) -> dict:
        return {
            "wafer": self.wafer,
            "date": self.string_date_format(),  # Ensure we save as string
            "chamber": self.chamber,
            "notes": self.notes,
            "masterType": self.master_type,
        }

    def string_date_format(self) -> str:
        """Helper to ensure the date is always a string for JSON."""
        dt = self.get_date()
        return self.format_date(dt) if dt else self.date
