"""
validation.py
This module contains functions for validating collection records.
"""

import json
import time
import logging
import requests
from cmr_metadata_validator.api_utils import get_record

logger = logging.getLogger(__name__)

def validate_a_record(provider, concept_id, native_id, metadata_spec_version, token):
    """
    Validates a collection record using the CMR validation API.

    Args:
        provider (str): The provider name.
        concept_id (str): The concept ID of the collection.
        native_id (str): The native ID of the collection.
        token (str): The authorization token for accessing the API.

    Returns:
        dict: A dictionary containing validation results.
    """
    try:
        time.sleep(1)
        data = get_record(concept_id, metadata_spec_version, token)

        headers = {
            'Content-Type': f'application/vnd.nasa.cmr.umm+json;version={metadata_spec_version}',
            'Cmr-Validate-Keywords': 'true',
            'Accept': 'application/json',
            'Client-Id': 'metadata_stewardship_validator'
            }
        logger.debug(f"Validation headers: {headers}")
        # Validate that data is not empty
        if not data:
            raise ValueError(f"No data retrieved for collection: {native_id}")

        url = (f"https://cmr.earthdata.nasa.gov"
                      f"/ingest/providers/{provider}/validate/collection/{concept_id}")
        logger.debug(f"Validated record url: {url}")
        # Make the POST request
        validating = requests.post(url, headers=headers, data=data.encode('utf-8'), timeout=300)
        if len(validating.text) < 1:
            if validating.status_code == 200:
                return {"no_errors": "Empty response with status code 200"}
            else:
                return {"errors": [f"Validation request failed with status code: "
                                   f"{validating.status_code}"]}
        validation_results = json.loads(validating.text)
        return validation_results
    except requests.RequestException as e:
        logger.error(f"Error on request validating record: {native_id} {concept_id} {e}")
        return {"errors": [f"Request error: {str(e)}"]}
    except ValueError as e:
        logger.error(f"Error ValueError validating record: {native_id} {concept_id} {e}")
        return {"errors": [str(e)]}
    except Exception as e:
        logger.error(f"Unexpected error validating record: {native_id} {concept_id} {e}")
        if 'data' in locals():
            logger.debug(f"Data content: {data}")
            try:
                json.loads(data)
                logger.info(f"Data for {native_id} is valid JSON.")
            except json.JSONDecodeError as json_error:
                logger.error(f"Error: Data for {native_id} is not valid JSON.")
                logger.error(f"JSON error: {json_error}")
                return {"errors": [f"Invalid JSON: {str(json_error)}"]}
        return {"errors": [f"Unexpected error: {str(e)}"]}
