#!/usr/bin/env python3
"""
Migration: Add session_label and period_type columns to monitoring_sessions.

session_label  - user-editable display name, e.g. "NRL-1 Sun 2/23 Night"
period_type    - one of: weekday_day | weekday_night | weekend_day | weekend_night
                 Auto-derived from started_at when NULL.

Period definitions (used in report stats table):
  weekday_day   Mon-Fri  07:00-22:00  -> Daytime (7AM-10PM)
  weekday_night Mon-Fri  22:00-07:00  -> Nighttime (10PM-7AM)
  weekend_day   Sat-Sun  07:00-22:00  -> Daytime (7AM-10PM)
  weekend_night Sat-Sun  22:00-07:00  -> Nighttime (10PM-7AM)

Run once inside the Docker container:
    docker exec terra-view python3 backend/migrate_add_session_period_type.py
"""
from pathlib import Path
from datetime import datetime

DB_PATH = Path("data/seismo_fleet.db")


def _derive_period_type(started_at_str: str) -> str | None:
    """Derive period_type from a started_at ISO datetime string."""
    if not started_at_str:
        return None
    try:
        dt = datetime.fromisoformat(started_at_str)
    except ValueError:
        return None
    is_weekend = dt.weekday() >= 5  # 5=Sat, 6=Sun
    is_night = dt.hour >= 22 or dt.hour < 7
    if is_weekend:
        return "weekend_night" if is_night else "weekend_day"
    else:
        return "weekday_night" if is_night else "weekday_day"


def _build_label(started_at_str: str, location_name: str | None, period_type: str | None) -> str | None:
    """Build a human-readable session label."""
    if not started_at_str:
        return None
    try:
        dt = datetime.fromisoformat(started_at_str)
    except ValueError:
        return None

    day_abbr = dt.strftime("%a")   # Mon, Tue, Sun, etc.
    date_str = dt.strftime("%-m/%-d")  # 2/23

    period_labels = {
        "weekday_day":   "Day",
        "weekday_night": "Night",
        "weekend_day":   "Day",
        "weekend_night": "Night",
    }
    period_str = period_labels.get(period_type or "", "")

    parts = []
    if location_name:
        parts.append(location_name)
    parts.append(f"{day_abbr} {date_str}")
    if period_str:
        parts.append(period_str)
    return " — ".join(parts)


def migrate():
    import sqlite3

    if not DB_PATH.exists():
        print(f"Database not found at {DB_PATH}. Are you running from /home/serversdown/terra-view?")
        return

    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    cur = conn.cursor()

    # 1. Add columns (idempotent)
    cur.execute("PRAGMA table_info(monitoring_sessions)")
    existing_cols = {row["name"] for row in cur.fetchall()}

    for col, typedef in [("session_label", "TEXT"), ("period_type", "TEXT")]:
        if col not in existing_cols:
            cur.execute(f"ALTER TABLE monitoring_sessions ADD COLUMN {col} {typedef}")
            conn.commit()
            print(f"✓ Added column {col} to monitoring_sessions")
        else:
            print(f"○ Column {col} already exists — skipping ALTER TABLE")

    # 2. Backfill existing rows
    cur.execute(
        """SELECT ms.id, ms.started_at, ms.location_id
           FROM monitoring_sessions ms
           WHERE ms.period_type IS NULL OR ms.session_label IS NULL"""
    )
    sessions = cur.fetchall()
    print(f"Backfilling {len(sessions)} session(s)...")

    updated = 0
    for row in sessions:
        session_id = row["id"]
        started_at = row["started_at"]
        location_id = row["location_id"]

        # Look up location name
        location_name = None
        if location_id:
            cur.execute("SELECT name FROM monitoring_locations WHERE id = ?", (location_id,))
            loc_row = cur.fetchone()
            if loc_row:
                location_name = loc_row["name"]

        period_type = _derive_period_type(started_at)
        label = _build_label(started_at, location_name, period_type)

        cur.execute(
            "UPDATE monitoring_sessions SET period_type = ?, session_label = ? WHERE id = ?",
            (period_type, label, session_id),
        )
        updated += 1

    conn.commit()
    conn.close()
    print(f"✓ Backfilled {updated} session(s).")
    print("Migration complete.")


if __name__ == "__main__":
    migrate()
