"""CLI tool for promoting dynamic tags to standard taxonomy.

Usage:
    python scripts/promote_dynamic_tag.py topic:gdpr compliance:regulatory:gdpr --description "GDPR compliance requirements"

Per Spec Section 4.4.4: Batch migration script
"""

import argparse
import asyncio
import sys
from pathlib import Path

# Add project root to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from sqlalchemy import create_engine
from sqlalchemy.orm import Session

from src.core.config import settings
from src.extraction_v2.taxonomy_loader import TaxonomyLoader
from src.services.tag_governance_service import TagPromotionService


def parse_args():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description="Promote a dynamic tag to standard taxonomy",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Promote topic:gdpr to compliance namespace
  python scripts/promote_dynamic_tag.py topic:gdpr compliance:regulatory:gdpr \\
      --description "GDPR compliance requirements" \\
      --examples "Must comply with GDPR Article 17" "GDPR data retention"

  # Promote to a specific profile
  python scripts/promote_dynamic_tag.py topic:pci_dss compliance:pci_dss \\
      --description "PCI DSS compliance" \\
      --profile fintech \\
      --no-taxonomy

  # List trending tags (dry run)
  python scripts/promote_dynamic_tag.py --list-trending --namespace topic
        """,
    )

    parser.add_argument(
        "old_tag",
        nargs="?",
        help="Current dynamic tag (e.g., topic:gdpr)",
    )
    parser.add_argument(
        "new_tag",
        nargs="?",
        help="New canonical tag (e.g., compliance:regulatory:gdpr)",
    )
    parser.add_argument(
        "-d",
        "--description",
        help="Description of the tag for taxonomy file",
    )
    parser.add_argument(
        "-e",
        "--examples",
        nargs="+",
        default=[],
        help="Example usages of the tag",
    )
    parser.add_argument(
        "-p",
        "--profile",
        help="Profile to add tag to (fintech, healthcare, automotive)",
    )
    parser.add_argument(
        "--no-taxonomy",
        action="store_true",
        help="Skip adding to taxonomy config file (DB migration only)",
    )
    parser.add_argument(
        "--list-trending",
        action="store_true",
        help="List trending dynamic tags (no promotion)",
    )
    parser.add_argument(
        "--namespace",
        help="Filter trending tags by namespace (topic, entity, tech, domain)",
    )
    parser.add_argument(
        "--min-usage",
        type=int,
        default=50,
        help="Minimum usage count for trending tags (default: 50)",
    )

    return parser.parse_args()


async def list_trending_tags(namespace: str = None, min_usage: int = 50):
    """List trending dynamic tags."""
    from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
    from sqlalchemy.orm import sessionmaker

    from src.services.tag_governance_service import DynamicTagAnalyzer

    # Create async engine
    async_db_url = settings.database_url
    engine = create_async_engine(async_db_url, echo=False)

    async_session_factory = sessionmaker(
        engine, class_=AsyncSession, expire_on_commit=False
    )

    async with async_session_factory() as session:
        analyzer = DynamicTagAnalyzer(session)
        trending = await analyzer.get_trending_tags(
            min_usage=min_usage,
            min_documents=3,
            namespace=namespace,
        )

        if not trending:
            print(f"\nNo trending tags found with usage >= {min_usage}")
            return

        print(f"\nTrending Tags (usage >= {min_usage}):")
        print("=" * 80)
        print(
            f"{'Tag':<40} {'Usage':>8} {'Docs':>6} {'Verified':>10} {'First/Last Seen'}"
        )
        print("-" * 80)

        for tag in trending:
            verified_pct = f"{tag['verified_ratio']*100:.1f}%"
            date_range = f"{tag['first_seen']} / {tag['last_seen']}"
            print(
                f"{tag['name']:<40} {tag['usage_count']:>8} "
                f"{tag['document_count']:>6} {verified_pct:>10} {date_range}"
            )

        print(f"\nTotal: {len(trending)} trending tags")

    await engine.dispose()


async def promote_tag_async(
    old_tag: str,
    new_tag: str,
    description: str,
    examples: list[str],
    profile: str = None,
    add_to_taxonomy: bool = True,
):
    """Promote a tag asynchronously."""
    from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
    from sqlalchemy.orm import sessionmaker

    # Create async engine
    async_db_url = settings.database_url
    engine = create_async_engine(async_db_url, echo=False)

    async_session_factory = sessionmaker(
        engine, class_=AsyncSession, expire_on_commit=False
    )

    async with async_session_factory() as session:
        # Load taxonomy
        taxonomy_loader = TaxonomyLoader(profile=profile)
        promotion_service = TagPromotionService(session, taxonomy_loader)

        print(f"\nPromoting tag:")
        print(f"  From: {old_tag}")
        print(f"  To:   {new_tag}")
        if profile:
            print(f"  Profile: {profile}")
        print()

        # Perform database migration
        print("Step 1: Migrating database records...")
        success, records_updated, error = await promotion_service.promote_tag(
            old_tag=old_tag,
            new_tag=new_tag,
            profile=profile,
        )

        if not success:
            print(f"✗ Error: {error}")
            await engine.dispose()
            sys.exit(1)

        print(f"✓ Successfully updated {records_updated} records")

        # Add to taxonomy file
        if add_to_taxonomy:
            print("\nStep 2: Adding to taxonomy configuration...")
            taxonomy_success, taxonomy_error = promotion_service.add_to_taxonomy_file(
                tag=new_tag,
                description=description,
                examples=examples,
                profile=profile,
            )

            if taxonomy_success:
                target_file = (
                    f"config/profiles/{profile}.json"
                    if profile
                    else "config/taxonomy/standard_tags.json"
                )
                print(f"✓ Added to {target_file}")
            else:
                print(f"✗ Failed to add to taxonomy: {taxonomy_error}")
        else:
            print("\nStep 2: Skipped (--no-taxonomy flag)")

        print(f"\n✓ Tag promotion complete!")
        print(f"  {old_tag} → {new_tag}")
        print(f"  Records updated: {records_updated}")

    await engine.dispose()


def main():
    """Main entry point."""
    args = parse_args()

    # List trending tags mode
    if args.list_trending:
        asyncio.run(list_trending_tags(args.namespace, args.min_usage))
        sys.exit(0)

    # Validate required arguments for promotion
    if not args.old_tag or not args.new_tag:
        print("Error: old_tag and new_tag are required for promotion")
        print("Use --list-trending to see candidates")
        sys.exit(1)

    if not args.description and not args.no_taxonomy:
        print("Error: --description is required when adding to taxonomy")
        print("Use --no-taxonomy to skip taxonomy file update")
        sys.exit(1)

    # Run promotion
    try:
        asyncio.run(
            promote_tag_async(
                old_tag=args.old_tag,
                new_tag=args.new_tag,
                description=args.description or "",
                examples=args.examples,
                profile=args.profile,
                add_to_taxonomy=not args.no_taxonomy,
            )
        )
    except Exception as e:
        print(f"\n✗ Error: {e}")
        import traceback

        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
