# Copyright (c) 2017 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com
#

from datetime import datetime

from voluptuous import All, Length, Match, Schema

from src.utils.time import utc_datetime_from_anything

# IDs
# ---
UUID = Schema(Match(r"^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$"))
CLOUD_ACCOUNT_ID = Schema(All(str, Length(min=12, max=12)))
CZ_ACCOUNT_ID = UUID
EXTERNAL_ID = Schema(All(str, Length(min=32, max=32)))
ORGANIZATION_ID = UUID

# Strings
# ----
KEBAB_CASE = Match(r"^[A-Za-z-]+$")


# Dates
# ----
def safe_date_parse(value):
    """Safely parse a date string or timestamp for schema validation."""
    try:
        # First try utc_datetime_from_anything which may raise ValueError now
        return utc_datetime_from_anything(value)
    except ValueError:
        # Fall back to explicit timestamp parsing if the string couldn't be parsed
        try:
            return datetime.fromtimestamp(float(value))
        except (ValueError, TypeError):
            # Re-raise with clear message if all parsing attempts failed
            raise ValueError(f"Could not parse '{value}' as a datetime or timestamp") from None


TIMESTAMP = Schema(All(safe_date_parse, lambda x: str(x.timestamp())))
