import argparse
import sys
import importlib

def main():
    parser = argparse.ArgumentParser(description="DocLatam CLI - Validation and Generation Tool")
    subparsers = parser.add_subparsers(dest="command", help="Command to execute")
    
    # Gen command
    gen_parser = subparsers.add_parser("gen", help="Generate a valid document")
    gen_parser.add_argument("country", help="Country code (br, ar, mx, etc.)")
    gen_parser.add_argument("doc", help="Document type (cpf, cnpj, curp, etc.)")
    
    # Check command
    check_parser = subparsers.add_parser("check", help="Check if a document is valid")
    check_parser.add_argument("country", help="Country code")
    check_parser.add_argument("doc", help="Document type")
    check_parser.add_argument("value", help="Document value to check")
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        sys.exit(1)
        
    try:
        # Import module dynamically
        # e.g. doclatam.br.cpf
        module_name = f"doclatam.{args.country}.{args.doc}"
        try:
            module = importlib.import_module(module_name)
        except ImportError:
             print(f"Error: Module {module_name} not found. Check country and document code.")
             sys.exit(1)

        validator_class = None
        target_name = args.doc.lower().replace('_', '')
        
        # Try to find the validator class
        for name, obj in vars(module).items():
            if isinstance(obj, type) and hasattr(obj, 'validate'):
                # Check if it's not BaseValidator imported
                if name == 'BaseValidator':
                    continue
                    
                if name.lower().replace('_', '') == target_name:
                    validator_class = obj
                    break
        
        # Fallback: grab the first class that looks like a validator if exact match fails
        if not validator_class:
            for name, obj in vars(module).items():
                 if isinstance(obj, type) and hasattr(obj, 'validate') and hasattr(obj, 'generate'):
                     if name != 'BaseValidator':
                         validator_class = obj
                         break

        if not validator_class:
            print(f"Error: Could not find validator class for {args.doc} in {args.country}")
            sys.exit(1)
            
        if args.command == "gen":
            if not hasattr(validator_class, 'generate'):
                 print(f"Error: {validator_class.__name__} does not support generation.")
                 sys.exit(1)
                 
            val = validator_class.generate()
            print(val)
            
            # Try clipboard
            try:
                import pyperclip
                pyperclip.copy(val)
                print("(Copied to clipboard)")
            except ImportError:
                pass
                
        elif args.command == "check":
            is_valid = validator_class.validate(args.value)
            if is_valid:
                print(f"✅ Valid {validator_class.__name__}")
                sys.exit(0)
            else:
                print(f"❌ Invalid {validator_class.__name__}")
                sys.exit(1)
                
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
