"""Majis ITL in JSON format sub-module."""

import json
from pathlib import Path

from planetary_coverage.events import EventWindow

from .mapping import JSON_MAPPING
from .schema import MAJIS_ITL_SCHEMAS


def read_itl_json(fname: str | Path) -> list[EventWindow]:
    """Read ITL file in JSON format.

    ITL are validated against Juice SOC and Majis schema.

    """
    data = json.loads(Path(fname).read_text())

    for schema in MAJIS_ITL_SCHEMAS:
        schema.validate(data)

    # Check filename match the one in the file
    filename = Path(data['header']['filename'])
    if not filename or filename.name != fname.name:
        raise FileNotFoundError(filename)

    # Set default values
    defaults = {
        'ITL': Path(filename),
        'COMMENTS': '',
    }

    return [
        EventWindow(
            obs['name'],
            _parse_json(obs, defaults=defaults),
        )
        for obs in data['timeline']
        # Filter only Majis observations
        if obs['instrument'] == 'MAJIS'
    ]


def _parse_json(obs: dict, defaults: dict | None = None) -> dict:
    """Map ITL JSON to timeline keys."""
    # Extract parameters
    params = obs.pop('parameters')

    # Convert JSON keys to EPS keys
    content = {
        JSON_MAPPING.get(key, key.upper()): value for key, value in (obs | params).items()
    }

    # Add extra keys
    content['PRIME'] = content.get('OBSERVATION_TYPE') == 'PRIME'

    # Add default keys (if not present)
    for key, value in defaults.items():
        if key not in content:
            content[key] = value

    # Put the comments at the end (always present from defaults)
    content['COMMENTS'] = content.pop('COMMENTS')

    return content
