# scans around the current location searching for a star

# stops immediately when one or more stars are detected

import time

import signal


#--------photo stuff ---

clr.AddReference("SharpCap.Base")

from SharpCap.Base import StarDetectionParameters


# ── raster Parameters ──────────────────────────────────────────────

DEG           = 2.0    # degrees in all directions

AZ_RATE       = 120.0  # 0.5°/s  (sidereal multiples)

ALT_DEG     = 0.5    # how many degrees between sweeps

POLL_TIME = 0.33


# ─── photo parameters ────────────────────────────────────────────────

params = StarDetectionParameters()

params.MaxCount = 100

params.MinSize = 1

params.MaxSize = 50

params.SuppressHotPixels = True


# ───────────────────────────────────────────────────

ALT_RATIO     = ALT_DEG/(4*DEG)    # Alt rate as fraction of Az rate

ALT_RATE   = AZ_RATE * ALT_RATIO

RASTER_ALT = DEG * 2.0



# ───────────────────────────────────────────────────


mount = SharpCap.Mounts.SelectedMount


def stop_slew(signum=None, frame=None):

    mount.MoveAxis(0, 0.0)

    mount.MoveAxis(1, 0.0)

    print("Slew stopped.")

    print(f"FINAL  Alt: {mount.Altitude:.4f}°  |  Az: {mount.Azimuth:.4f}°")

    if signum is not None:

        raise SystemExit(0)


signal.signal(signal.SIGTERM, stop_slew)

signal.signal(signal.SIGINT,  stop_slew)


start_alt = mount.Altitude

start_az  = mount.Azimuth

print(f"START  Alt: {start_alt:.4f}°  |  Az: {start_az:.4f}°")


# ── boundary checks (Alt only — Az is circular, no hard limits) ────

ALT_LIMIT = 85.0


if start_alt + DEG > ALT_LIMIT:

    print(f"ERROR: Alt {start_alt:.2f}° + sweep {DEG}° would exceed {ALT_LIMIT}°. Aborting.")

    raise SystemExit(1)

if start_alt - DEG < 0.0:

    print(f"ERROR: Alt {start_alt:.2f}° - sweep {DEG}° would go below 0°. Aborting.")

    raise SystemExit(1)


delta_alt = DEG

delta_az  = DEG


# ── Phase 1: diagonal move down-left ────────────────────────

print("move diagonally down-left")

mount.MoveAxis(0, -AZ_RATE)      # azimuth left

mount.MoveAxis(1, -AZ_RATE)     # altitude down


try:

    while True:

        time.sleep(POLL_TIME)


        cur_alt = mount.Altitude

        cur_az  = mount.Azimuth


        d_alt = cur_alt - start_alt

        d_az  = cur_az - start_az


        #print(f"[DIAG] ΔAlt: {d_alt:+.4f}°  |  ΔAz: {d_az:+.4f}°")


        if d_alt <= -DEG:

            print("Stopped: altitude limit reached.")

            break

        if d_az <= -DEG:

            print("Stopped: azimuth limit reached.")

            break

finally:

    mount.MoveAxis(0, 0.0)

    mount.MoveAxis(1, 0.0)

    print(f"STOP  Alt: {mount.Altitude:.4f}°  |  Az: {mount.Azimuth:.4f}°")


# ── Phase 2: raster sweep ────────────────────────────────────

print(f"RASTER START  Alt: {mount.Altitude:.4f}°  |  Az: {mount.Azimuth:.4f}°")


az_dir = 1.0

stars = []

star_found = False

mount.MoveAxis(0, az_dir * AZ_RATE)

mount.MoveAxis(1, ALT_RATE)


def az_delta(current, reference):

    """Signed angular difference current - reference, wrapped to (-180, 180]."""

    return ((current - reference + 180.0) % 360.0) - 180.0


try:

    while True:

        time.sleep(POLL_TIME)

        delta_alt = mount.Altitude - start_alt

        delta_az  = az_delta(mount.Azimuth, start_az)

        #print(f"[RASTER] ΔAlt: {delta_alt:+.4f}°  |  ΔAz: {delta_az:+.4f}°  |  Az dir: {'+' if az_dir > 0 else '-'}")


        # detect stars

        captured = SharpCap.SelectedCamera.GetDisplayedFrame()

        stars = captured.Frame.DetectStars(params)

        #print(len(stars), "stars found")


        if len(stars) > 0:

            star_found = True

            print(f"Star(s) found — stopping at Alt: {mount.Altitude:.4f}°  |  Az: {mount.Azimuth:.4f}°")

            break


        if delta_alt >= RASTER_ALT:

            print("Raster complete — Alt limit reached.")

            break

        if az_dir > 0 and delta_az >= DEG:

            az_dir = -1.0

            mount.MoveAxis(0, az_dir * AZ_RATE)

            print("-- Az reverse: going left --")

            print(f"[RASTER] ΔAlt: {delta_alt:+.4f}°  |  ΔAz: {delta_az:+.4f}°  |  Az dir: {'+' if az_dir > 0 else '-'}")

        elif az_dir < 0 and delta_az <= -DEG:

            az_dir = 1.0

            mount.MoveAxis(0, az_dir * AZ_RATE)

            print("-- Az reverse: going right --")

            print(f"[RASTER] ΔAlt: {delta_alt:+.4f}°  |  ΔAz: {delta_az:+.4f}°  |  Az dir: {'+' if az_dir > 0 else '-'}")

finally:

    stop_slew()

    time.sleep(0.5)

    if star_found:

        print(f"Staying at star location  Alt: {mount.Altitude:.4f}°  |  Az: {mount.Azimuth:.4f}°")

    else:

        print("No stars found — slewing home", start_alt, start_az)

        mount.SlewToAltAz(start_alt, start_az)

        time.sleep(4.0)

        print(mount.Altitude, mount.Azimuth)