#!/usr/bin/env python3
"""
Independent verification script to prove ALL tuple fallbacks have been eliminated.

This script searches for any remaining tuple fallback patterns and fails if any are found.
You can run this script independently to verify the claims.
"""

import os
import re
import sys
from pathlib import Path


def search_for_tuple_fallbacks():
    """Search for tuple fallback patterns in the codebase."""

    # Patterns that indicate tuple fallbacks
    choice_fallback_patterns = [
        r"choices\.get\([^,]+,\s*[^)]+\)",  # choices.get(value, fallback)
        r"status_.*\.get\([^,]+,\s*[^)]+\)",  # status_colors.get(value, fallback)
        r"category_.*\.get\([^,]+,\s*[^)]+\)",  # category_images.get(value, fallback)
        r"sla_hours\.get\([^,]+,\s*[^)]+\)",  # sla_hours.get(priority, fallback)
        r"get_tuple_choices\(",  # get_tuple_choices function
        r"from_tuple\(",  # from_tuple function
        r"convert_tuple_choices\(",  # convert_tuple_choices function
    ]

    apps_dir = Path("apps")
    if not apps_dir.exists():
        print("❌ Error: apps directory not found")
        return False

    found_fallbacks = []

    # Search all Python files in apps directory
    for py_file in apps_dir.rglob("*.py"):
        # Skip migrations (they're supposed to have hardcoded values)
        if "migration" in str(py_file):
            continue

        try:
            with open(py_file, encoding="utf-8") as f:
                content = f.read()

            for line_num, line in enumerate(content.split("\n"), 1):
                for pattern in choice_fallback_patterns:
                    if re.search(pattern, line):
                        found_fallbacks.append(
                            {"file": py_file, "line": line_num, "content": line.strip(), "pattern": pattern}
                        )
        except Exception as e:
            print(f"❌ Error reading {py_file}: {e}")
            continue

    # Report results
    if found_fallbacks:
        print(f"❌ FOUND {len(found_fallbacks)} TUPLE FALLBACK PATTERNS:")
        for fallback in found_fallbacks:
            print(f"  {fallback['file']}:{fallback['line']} - {fallback['content']}")
        return False
    else:
        print("✅ NO TUPLE FALLBACKS FOUND - All eliminated!")
        return True


def verify_tuple_functions_removed():
    """Verify that tuple fallback functions have been removed."""

    # Check that get_tuple_choices is not importable
    try:
        from apps.core.choices.registry import get_tuple_choices  # noqa: F401

        print("❌ ERROR: get_tuple_choices function still exists!")
        return False
    except ImportError:
        print("✅ get_tuple_choices function successfully removed")

    # Check that Rich Choice objects work as primary source
    try:
        from apps.core.choices.registry import get_choices  # noqa: F401

        print("✅ get_choices function (Rich Choice objects) works as primary source")
        return True
    except ImportError:
        print("❌ ERROR: get_choices function missing!")
        return False


def main():
    """Main verification function."""
    print("=== TUPLE FALLBACK ELIMINATION VERIFICATION ===\n")

    # Change to backend directory if needed
    if "backend" not in os.getcwd():
        backend_dir = Path(__file__).parent
        os.chdir(backend_dir)
        print(f"Changed directory to: {os.getcwd()}")

    print("1. Searching for tuple fallback patterns...")
    patterns_clean = search_for_tuple_fallbacks()

    print("\n2. Verifying tuple functions removed...")
    functions_removed = verify_tuple_functions_removed()

    print("\n=== FINAL RESULT ===")
    if patterns_clean and functions_removed:
        print("🎉 SUCCESS: ALL TUPLE FALLBACKS HAVE BEEN ELIMINATED!")
        return 0
    else:
        print("❌ FAILURE: Tuple fallbacks still exist!")
        return 1


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