"""
Migration: add period_start_hour and period_end_hour to monitoring_sessions.

Run once:
    python backend/migrate_add_session_period_hours.py

Or inside the container:
    docker exec terra-view python3 backend/migrate_add_session_period_hours.py
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from backend.database import engine
from sqlalchemy import text

def run():
    with engine.connect() as conn:
        # Check which columns already exist
        result = conn.execute(text("PRAGMA table_info(monitoring_sessions)"))
        existing = {row[1] for row in result}

        added = []
        for col, definition in [
            ("period_start_hour", "INTEGER"),
            ("period_end_hour",   "INTEGER"),
        ]:
            if col not in existing:
                conn.execute(text(f"ALTER TABLE monitoring_sessions ADD COLUMN {col} {definition}"))
                added.append(col)
            else:
                print(f"  Column '{col}' already exists — skipping.")

        conn.commit()

        if added:
            print(f"  Added columns: {', '.join(added)}")
        print("Migration complete.")

if __name__ == "__main__":
    run()
