#!/usr/bin/env python3
"""
Script to seed service modules into the compliance database.

Usage:
    python -m compliance.scripts.seed_service_modules

This script can be run standalone or imported for use in migrations.
"""

import sys
import logging
from pathlib import Path

# Add parent directory to path to allow imports
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from classroom_engine.database import SessionLocal
from compliance.services.seeder import ComplianceSeeder
from compliance.data.service_modules import get_service_count

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def seed_service_modules():
    """Seed service modules and their regulation mappings."""
    logger.info("Starting service module seeding...")

    db = SessionLocal()
    try:
        seeder = ComplianceSeeder(db)

        # Get total services available
        total_services = get_service_count()
        logger.info(f"Found {total_services} services in BREAKPILOT_SERVICES")

        # Seed service modules
        result = seeder.seed_service_modules_only()

        logger.info(f"✓ Successfully seeded {result} items (modules + regulation mappings)")
        return result

    except Exception as e:
        logger.error(f"✗ Seeding failed: {e}", exc_info=True)
        raise
    finally:
        db.close()


def seed_all_compliance_data():
    """Seed all compliance data including service modules."""
    logger.info("Starting full compliance database seeding...")

    db = SessionLocal()
    try:
        seeder = ComplianceSeeder(db)
        results = seeder.seed_all(force=False)

        logger.info("✓ Seeding completed successfully!")
        logger.info(f"  - Regulations: {results['regulations']}")
        logger.info(f"  - Controls: {results['controls']}")
        logger.info(f"  - Requirements: {results['requirements']}")
        logger.info(f"  - Control Mappings: {results['mappings']}")
        logger.info(f"  - Risks: {results['risks']}")
        logger.info(f"  - Service Modules: {results['service_modules']}")
        logger.info(f"  - Module-Regulation Mappings: {results['module_regulation_mappings']}")

        return results

    except Exception as e:
        logger.error(f"✗ Seeding failed: {e}", exc_info=True)
        raise
    finally:
        db.close()


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Seed compliance database")
    parser.add_argument(
        "--mode",
        choices=["modules", "all"],
        default="modules",
        help="Seeding mode: 'modules' (service modules only) or 'all' (complete database)"
    )

    args = parser.parse_args()

    if args.mode == "modules":
        seed_service_modules()
    else:
        seed_all_compliance_data()
