import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import astropy.units as u
from astropy.coordinates import SkyCoord
from astropy.time import Time
from astroplan import FixedTarget, is_event_observable
from saltshaker import (
    get_salt_observer,
    SaltTrackLengthConstraint,
    SaltMoonConstraint
)

# 1. Setup the Observer and Target
observer = get_salt_observer()
target = FixedTarget(coord=SkyCoord.from_name('Sirius'), name='Sirius')

# 2. Define Constraints (e.g., Gray moon and minimum 20 min track)
constraints = [
    SaltTrackLengthConstraint(min_track_length=20 * u.minute),
    SaltMoonConstraint(max_illumination=0.5)
]

# 3. Evaluate over a 48-hour period
start_time = Time('2026-01-15 12:00:00')
times = start_time + np.linspace(0, 48, 300) * u.hour

# 4. Calculate observability and night/day states
observable = is_event_observable(constraints, observer, target, times=times)[0]
is_night = observer.is_night(times)

# 5. Visualize the Timeline
fig, ax = plt.subplots(figsize=(10, 2.5))

# Shade the Night Time (in light grey)
ax.fill_between(times.plot_date, 0, 1, where=is_night,
                color='lightgrey', alpha=0.5, label='Night Time')

# Shade the Observability Window (in blue)
ax.fill_between(times.plot_date, 0, 1, where=observable,
                color='blue', alpha=0.7, label='Meets Constraints')

# Formatting the plot
ax.set_yticks([])
ax.set_ylim(0, 1)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M\n%b %d'))

plt.title(f"Estimated Observability: {target.name}", fontsize=12, fontweight='bold')
plt.xlabel("Time (UTC)")
plt.legend(loc='upper right', bbox_to_anchor=(1, 1.3), ncol=2, frameon=False)
plt.tight_layout()
plt.show()