#!/usr/bin/env python3
"""
Database initialization script for Projects system.

This script creates the new project management tables and populates
the project_types table with default templates.

Usage:
    python -m backend.init_projects_db
"""

from sqlalchemy.orm import Session
from backend.database import engine, SessionLocal
from backend.models import (
    Base,
    ProjectType,
    Project,
    MonitoringLocation,
    UnitAssignment,
    ScheduledAction,
    MonitoringSession,
    DataFile,
)
from datetime import datetime


def init_project_types(db: Session):
    """Initialize default project types."""
    project_types = [
        {
            "id": "sound_monitoring",
            "name": "Sound Monitoring",
            "description": "Noise monitoring projects with sound level meters and NRLs (Noise Recording Locations)",
            "icon": "volume-2",  # Lucide icon name
            "supports_sound": True,
            "supports_vibration": False,
        },
        {
            "id": "vibration_monitoring",
            "name": "Vibration Monitoring",
            "description": "Seismic/vibration monitoring projects with seismographs and monitoring points",
            "icon": "activity",  # Lucide icon name
            "supports_sound": False,
            "supports_vibration": True,
        },
        {
            "id": "combined",
            "name": "Combined Monitoring",
            "description": "Full-spectrum monitoring with both sound and vibration capabilities",
            "icon": "layers",  # Lucide icon name
            "supports_sound": True,
            "supports_vibration": True,
        },
    ]

    for pt_data in project_types:
        existing = db.query(ProjectType).filter_by(id=pt_data["id"]).first()
        if not existing:
            pt = ProjectType(**pt_data)
            db.add(pt)
            print(f"✓ Created project type: {pt_data['name']}")
        else:
            print(f"  Project type already exists: {pt_data['name']}")

    db.commit()


def create_tables():
    """Create all tables defined in models."""
    print("Creating project management tables...")
    Base.metadata.create_all(bind=engine)
    print("✓ Tables created successfully")


def main():
    print("=" * 60)
    print("Terra-View Projects System - Database Initialization")
    print("=" * 60)
    print()

    # Create tables
    create_tables()
    print()

    # Initialize project types
    db = SessionLocal()
    try:
        print("Initializing project types...")
        init_project_types(db)
        print()
        print("=" * 60)
        print("✓ Database initialization complete!")
        print("=" * 60)
        print()
        print("Next steps:")
        print("  1. Restart Terra-View to load new routes")
        print("  2. Navigate to /projects to create your first project")
        print("  3. Check documentation for API endpoints")
    except Exception as e:
        print(f"✗ Error during initialization: {e}")
        db.rollback()
        raise
    finally:
        db.close()


if __name__ == "__main__":
    main()
