#!/usr/bin/env python3
"""
NordaBiz - Migration Script: News Tables
=========================================

Creates the following tables via SQLAlchemy:
- company_news: News and mentions for companies
- user_notifications: In-app notifications for users

Usage:
    python migrate_add_news_tables.py [--dry-run]

Options:
    --dry-run    Show what would be created without executing

Author: Norda Biznes Development Team
Created: 2025-12-29
"""

import argparse
import sys
from datetime import datetime

# Import database components
from database import Base, engine, SessionLocal, CompanyNews, UserNotification

# Import for table inspection
from sqlalchemy import inspect


def check_existing_tables():
    """Check which tables already exist"""
    inspector = inspect(engine)
    existing_tables = inspector.get_table_names()
    return existing_tables


def migrate(dry_run: bool = False) -> bool:
    """
    Run the migration to create news tables.

    Args:
        dry_run: If True, only show what would be created

    Returns:
        True if successful, False otherwise
    """
    print("=" * 60)
    print("NordaBiz Migration: News Tables")
    print("=" * 60)
    print(f"Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print()

    # Check existing tables
    existing_tables = check_existing_tables()
    print(f"Existing tables in database: {len(existing_tables)}")

    # Tables to create
    tables_to_create = ['company_news', 'user_notifications']

    # Check status
    for table_name in tables_to_create:
        if table_name in existing_tables:
            print(f"  [EXISTS] {table_name}")
        else:
            print(f"  [TO CREATE] {table_name}")
    print()

    # Check if both tables already exist
    if all(t in existing_tables for t in tables_to_create):
        print("All tables already exist. Nothing to do.")
        return True

    if dry_run:
        print("[DRY RUN] Would create the following tables:")
        for table_name in tables_to_create:
            if table_name not in existing_tables:
                print(f"  - {table_name}")
        print()
        print("[DRY RUN] No changes made.")
        return True

    # Create tables
    print("Creating tables...")
    try:
        # Get only the tables we need to create
        tables_to_create_objs = []

        if 'company_news' not in existing_tables:
            tables_to_create_objs.append(CompanyNews.__table__)

        if 'user_notifications' not in existing_tables:
            tables_to_create_objs.append(UserNotification.__table__)

        # Create tables
        Base.metadata.create_all(bind=engine, tables=tables_to_create_objs)

        print()
        print("Tables created successfully!")

    except Exception as e:
        print(f"ERROR: Failed to create tables: {e}")
        return False

    # Verify creation
    print()
    print("Verifying creation...")
    new_existing_tables = check_existing_tables()

    success = True
    for table_name in tables_to_create:
        if table_name in new_existing_tables:
            print(f"  [OK] {table_name}")
        else:
            print(f"  [FAILED] {table_name}")
            success = False

    if success:
        print()
        print("=" * 60)
        print("Migration completed successfully!")
        print("=" * 60)

        # Show table info
        db = SessionLocal()
        try:
            news_count = db.query(CompanyNews).count()
            notif_count = db.query(UserNotification).count()
            print(f"company_news records: {news_count}")
            print(f"user_notifications records: {notif_count}")
        finally:
            db.close()
    else:
        print()
        print("ERROR: Migration failed!")

    return success


def show_table_info():
    """Display information about the news tables"""
    print()
    print("Table: company_news")
    print("-" * 40)
    print("Purpose: News and mentions for companies")
    print("Sources: Web search, social media, press")
    print("Features:")
    print("  - AI filtering (relevance_score)")
    print("  - AI summaries (ai_summary)")
    print("  - Moderation workflow")
    print("  - Multiple news types")
    print()
    print("Table: user_notifications")
    print("-" * 40)
    print("Purpose: In-app notifications for users")
    print("Features:")
    print("  - Read/unread tracking")
    print("  - Multiple notification types")
    print("  - Related entity links")
    print("  - Action URLs")


def main():
    parser = argparse.ArgumentParser(
        description="Create news tables in NordaBiz database"
    )
    parser.add_argument(
        '--dry-run',
        action='store_true',
        help='Show what would be created without executing'
    )
    parser.add_argument(
        '--info',
        action='store_true',
        help='Show information about the tables'
    )

    args = parser.parse_args()

    if args.info:
        show_table_info()
        return 0

    success = migrate(dry_run=args.dry_run)
    return 0 if success else 1


if __name__ == '__main__':
    sys.exit(main())
